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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
timeout-minutes: 10
name: lint
runs-on: ${{ github.repository == 'stainless-sdks/formalize-python' && 'depot-ubuntu-24.04' || 'ubuntu-latest' }}
if: github.event_name == 'push' || github.event.pull_request.head.repo.fork
if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata')
steps:
- uses: actions/checkout@v6

Expand All @@ -35,7 +35,7 @@ jobs:
run: ./scripts/lint

build:
if: github.event_name == 'push' || github.event.pull_request.head.repo.fork
if: (github.event_name == 'push' || github.event.pull_request.head.repo.fork) && (github.event_name != 'push' || github.event.head_commit.message != 'codegen metadata')
timeout-minutes: 10
name: build
permissions:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.prism.log
.stdy.log
_dev

__pycache__
Expand Down
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "1.3.0"
".": "1.4.0"
}
6 changes: 3 additions & 3 deletions .stats.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
configured_endpoints: 4
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/benchify%2Fformalize-68622707ed43c0c2934d378d9c87b746a95967ca3d2764b0889889f771317611.yml
openapi_spec_hash: e46e13174b96c49dbca07afd1a97c2ed
configured_endpoints: 2
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/benchify/formalize-3c52b5aeafb4d26b3650c62776527aecbb19df133407809a00acdf8b365e4ceb.yml
openapi_spec_hash: b09b4f07b4f2796145d9a607d6dfa2e5
config_hash: 63fdaff946185aaff06e9fd59a007649
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
# Changelog

## 1.4.0 (2026-05-01)

Full Changelog: [v1.3.0...v1.4.0](https://github.com/Benchify/formalize-python/compare/v1.3.0...v1.4.0)

### Features

* get rid of legacy routes ([5da5279](https://github.com/Benchify/formalize-python/commit/5da527973b1d2d994bf3dfeccd5e69bc65aa12f5))
* **internal:** implement indices array format for query and form serialization ([563c58c](https://github.com/Benchify/formalize-python/commit/563c58cb935ec2baf52614b9a2b8f7f2ac4178e7))
* support setting headers via env ([799fdc0](https://github.com/Benchify/formalize-python/commit/799fdc05dfafc29f30f553861ec6ee524410b20a))


### Bug Fixes

* **client:** preserve hardcoded query params when merging with user params ([cb1116e](https://github.com/Benchify/formalize-python/commit/cb1116e13d34679fa2cd73fe17cbf3bfa74c106b))
* ensure file data are only sent as 1 parameter ([f2e61d8](https://github.com/Benchify/formalize-python/commit/f2e61d8e07e220de2b785c0b9985e403bf97fca1))
* sanitize endpoint path params ([f9b35f6](https://github.com/Benchify/formalize-python/commit/f9b35f6d04184131168dde207f7d8dac47a7ecd7))
* use correct field name format for multipart file arrays ([6630691](https://github.com/Benchify/formalize-python/commit/66306915b66d66bc80074de143ce101ba7f3c3c0))


### Performance Improvements

* **client:** optimize file structure copying in multipart requests ([aa8ebe4](https://github.com/Benchify/formalize-python/commit/aa8ebe4e973bdabed6e614b86ea7662918925955))


### Chores

* **ci:** skip lint on metadata-only changes ([f3ad8e3](https://github.com/Benchify/formalize-python/commit/f3ad8e3e3f5a4f4a49bad8f60ff3202d5e487152))
* **internal:** more robust bootstrap script ([f3e33d5](https://github.com/Benchify/formalize-python/commit/f3e33d5e7b7652b0764ae2f39ca186aaba690a4c))
* **internal:** reformat pyproject.toml ([cc326cf](https://github.com/Benchify/formalize-python/commit/cc326cfca752a635b78a66cc326fae8b58f62ad4))
* **internal:** update gitignore ([05eef18](https://github.com/Benchify/formalize-python/commit/05eef18b272c2be5047fa6c51504fc1e49aca1cb))

## 1.3.0 (2026-03-17)

Full Changelog: [v1.2.0...v1.3.0](https://github.com/Benchify/formalize-python/compare/v1.2.0...v1.3.0)
Expand Down
12 changes: 0 additions & 12 deletions api.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,3 @@ Methods:

- <code title="post /api/v1/contracts/{contract_id}/audit">client.api.v1.contracts.audit.<a href="./src/formalize/resources/api/v1/contracts/audit.py">create</a>(contract_id, \*\*<a href="src/formalize/types/api/v1/contracts/audit_create_params.py">params</a>) -> <a href="./src/formalize/types/api/v1/contracts/audit_create_response.py">AuditCreateResponse</a></code>
- <code title="post /api/v1/contracts/{contract_id}/audit/batch">client.api.v1.contracts.audit.<a href="./src/formalize/resources/api/v1/contracts/audit.py">batch</a>(contract_id, \*\*<a href="src/formalize/types/api/v1/contracts/audit_batch_params.py">params</a>) -> <a href="./src/formalize/types/api/v1/contracts/audit_batch_response.py">AuditBatchResponse</a></code>

## Contracts

Methods:

- <code title="post /api/contracts/{contract_id}/optimize">client.api.contracts.<a href="./src/formalize/resources/api/contracts/contracts.py">optimize</a>(contract_id, \*\*<a href="src/formalize/types/api/contract_optimize_params.py">params</a>) -> object</code>

### OptimizationResults

Methods:

- <code title="get /api/contracts/{contract_id}/optimization-results">client.api.contracts.optimization_results.<a href="./src/formalize/resources/api/contracts/optimization_results.py">retrieve_optimization_results</a>(contract_id) -> object</code>
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "benchify"
version = "1.3.0"
version = "1.4.0"
description = "The official Python library for the formalize API"
dynamic = ["readme"]
license = "Apache-2.0"
Expand Down Expand Up @@ -154,7 +154,7 @@ 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/formalize/_files.py', '_dev/.*.py', 'tests/.*']
exclude = ["src/formalize/_files.py", "_dev/.*.py", "tests/.*"]

strict_equality = true
implicit_reexport = true
Expand Down
2 changes: 1 addition & 1 deletion scripts/bootstrap
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ set -e

cd "$(dirname "$0")/.."

if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "$SKIP_BREW" != "1" ] && [ -t 0 ]; then
if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "${SKIP_BREW:-}" != "1" ] && [ -t 0 ]; then
brew bundle check >/dev/null 2>&1 || {
echo -n "==> Install Homebrew dependencies? (y/N): "
read -r response
Expand Down
4 changes: 4 additions & 0 deletions src/formalize/_base_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,10 @@ def _build_request(
files = cast(HttpxRequestFiles, ForceMultipartDict())

prepared_url = self._prepare_url(options.url)
# preserve hard-coded query params from the url
if params and prepared_url.query:
params = {**dict(prepared_url.params.items()), **params}
prepared_url = prepared_url.copy_with(raw_path=prepared_url.raw_path.split(b"?", 1)[0])
if "_" in prepared_url.host:
# work around https://github.com/encode/httpx/discussions/2880
kwargs["extensions"] = {"sni_hostname": prepared_url.host.replace("_", "-")}
Expand Down
24 changes: 23 additions & 1 deletion src/formalize/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@
RequestOptions,
not_given,
)
from ._utils import is_given, get_async_library
from ._utils import (
is_given,
is_mapping_t,
get_async_library,
)
from ._compat import cached_property
from ._models import SecurityOptions
from ._version import __version__
Expand Down Expand Up @@ -96,6 +100,15 @@ def __init__(
if base_url is None:
base_url = f"https://api.example.com"

custom_headers_env = os.environ.get("FORMALIZE_CUSTOM_HEADERS")
if custom_headers_env is not None:
parsed: dict[str, str] = {}
for line in custom_headers_env.split("\n"):
colon = line.find(":")
if colon >= 0:
parsed[line[:colon].strip()] = line[colon + 1 :].strip()
default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})}

super().__init__(
version=__version__,
base_url=base_url,
Expand Down Expand Up @@ -303,6 +316,15 @@ def __init__(
if base_url is None:
base_url = f"https://api.example.com"

custom_headers_env = os.environ.get("FORMALIZE_CUSTOM_HEADERS")
if custom_headers_env is not None:
parsed: dict[str, str] = {}
for line in custom_headers_env.split("\n"):
colon = line.find(":")
if colon >= 0:
parsed[line[:colon].strip()] = line[colon + 1 :].strip()
default_headers = {**parsed, **(default_headers if is_mapping_t(default_headers) else {})}

super().__init__(
version=__version__,
base_url=base_url,
Expand Down
56 changes: 53 additions & 3 deletions src/formalize/_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import io
import os
import pathlib
from typing import overload
from typing_extensions import TypeGuard
from typing import Sequence, cast, overload
from typing_extensions import TypeVar, TypeGuard

import anyio

Expand All @@ -17,7 +17,9 @@
HttpxFileContent,
HttpxRequestFiles,
)
from ._utils import is_tuple_t, is_mapping_t, is_sequence_t
from ._utils import is_list, is_mapping, is_tuple_t, is_mapping_t, is_sequence_t

_T = TypeVar("_T")


def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
Expand Down Expand Up @@ -121,3 +123,51 @@ async def async_read_file_content(file: FileContent) -> HttpxFileContent:
return await anyio.Path(file).read_bytes()

return file


def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T:
"""Copy only the containers along the given paths.

Used to guard against mutation by extract_files without copying the entire structure.
Only dicts and lists that lie on a path are copied; everything else
is returned by reference.

For example, given paths=[["foo", "files", "file"]] and the structure:
{
"foo": {
"bar": {"baz": {}},
"files": {"file": <content>}
}
}
The root dict, "foo", and "files" are copied (they lie on the path).
"bar" and "baz" are returned by reference (off the path).
"""
return _deepcopy_with_paths(item, paths, 0)


def _deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]], index: int) -> _T:
if not paths:
return item
if is_mapping(item):
key_to_paths: dict[str, list[Sequence[str]]] = {}
for path in paths:
if index < len(path):
key_to_paths.setdefault(path[index], []).append(path)

# if no path continues through this mapping, it won't be mutated and copying it is redundant
if not key_to_paths:
return item

result = dict(item)
for key, subpaths in key_to_paths.items():
if key in result:
result[key] = _deepcopy_with_paths(result[key], subpaths, index + 1)
return cast(_T, result)
if is_list(item):
array_paths = [path for path in paths if index < len(path) and path[index] == "<array>"]

# if no path expects a list here, nothing will be mutated inside it - return by reference
if not array_paths:
return cast(_T, item)
return cast(_T, [_deepcopy_with_paths(entry, array_paths, index + 1) for entry in item])
return item
13 changes: 6 additions & 7 deletions src/formalize/_qs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,13 @@

from typing import Any, List, Tuple, Union, Mapping, TypeVar
from urllib.parse import parse_qs, urlencode
from typing_extensions import Literal, get_args
from typing_extensions import get_args

from ._types import NotGiven, not_given
from ._types import NotGiven, ArrayFormat, NestedFormat, not_given
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
Expand Down Expand Up @@ -101,7 +97,10 @@ def _stringify_item(
items.extend(self._stringify_item(key, item, opts))
return items
elif array_format == "indices":
raise NotImplementedError("The array indices format is not supported yet")
items = []
for i, item in enumerate(value):
items.extend(self._stringify_item(f"{key}[{i}]", item, opts))
return items
elif array_format == "brackets":
items = []
key = key + "[]"
Expand Down
3 changes: 3 additions & 0 deletions src/formalize/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
ModelT = TypeVar("ModelT", bound=pydantic.BaseModel)
_T = TypeVar("_T")

ArrayFormat = Literal["comma", "repeat", "indices", "brackets"]
NestedFormat = Literal["dots", "brackets"]


# Approximates httpx internal ProxiesTypes and RequestFiles types
# while adding support for `PathLike` instances
Expand Down
2 changes: 1 addition & 1 deletion src/formalize/_utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from ._path import path_template as path_template
from ._sync import asyncify as asyncify
from ._proxy import LazyProxy as LazyProxy
from ._utils import (
Expand All @@ -23,7 +24,6 @@
coerce_integer as coerce_integer,
file_from_path as file_from_path,
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,
Expand Down
Loading
Loading