Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

release: 0.3.14 #152

Merged
merged 19 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
1f98257
docs: add some missing inline documentation (#151)
stainless-bot Sep 13, 2023
9cac11b
ci: add workflow to handle release PR edit (#153)
stainless-bot Sep 14, 2023
da6ccb1
fix(client): properly configure model set fields (#154)
stainless-bot Sep 14, 2023
46386f8
feat(client): retry on 408 Request Timeout (#155)
stainless-bot Sep 14, 2023
00f5a19
chore(internal): add helpers (#156)
stainless-bot Sep 14, 2023
59fe4e3
ci: configure release PR title (#158)
stainless-bot Sep 15, 2023
e22f0e7
ci: fix handle-release-pr-title-edit workflow (#159)
stainless-bot Sep 15, 2023
43544a6
feat(types): improve params type names (#160)
stainless-bot Sep 19, 2023
76cfcf9
fix(client): don't error by default for unexpected content types (#161)
stainless-bot Sep 22, 2023
329b307
chore(internal): move error classes from _base_exceptions to _excepti…
stainless-bot Sep 22, 2023
e7aa3e7
feat(package): export a root error type (#163)
stainless-bot Sep 25, 2023
8042473
chore(tests): improve raw response test (#166)
stainless-bot Sep 27, 2023
bb7d129
ci: only run workflow handle-release-pr-title-edit for release PRs (#…
stainless-bot Oct 2, 2023
afeabf1
feat(client): handle retry-after header with a date format (#168)
stainless-bot Oct 2, 2023
b472605
test: rename `API_BASE_URL` to `TEST_API_BASE_URL` (#169)
stainless-bot Oct 2, 2023
4c5289e
feat(client): add forwards-compatible pydantic methods (#171)
stainless-bot Oct 9, 2023
351095b
docs: update readme (#172)
stainless-bot Oct 11, 2023
25046c4
feat(client): add support for passing in a httpx client (#173)
stainless-bot Oct 11, 2023
432a3ac
release: 0.3.14
stainless-bot Oct 11, 2023
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
24 changes: 24 additions & 0 deletions .github/workflows/handle-release-pr-title-edit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: Handle release PR title edits
on:
pull_request:
types:
- edited
- unlabeled

jobs:
update_pr_content:
name: Update pull request content
if: |
((github.event.action == 'edited' && github.event.changes.title.from != github.event.pull_request.title) ||
(github.event.action == 'unlabeled' && github.event.label.name == 'autorelease: custom version')) &&
startsWith(github.event.pull_request.head.ref, 'release-please--') &&
github.event.pull_request.state == 'open' &&
github.event.sender.login != 'stainless-bot' &&
github.repository == 'anthropics/anthropic-sdk-python'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: stainless-api/trigger-release-please@v1
with:
repo: ${{ github.event.repository.full_name }}
stainless-api-key: ${{ secrets.STAINLESS_API_KEY }}
2 changes: 1 addition & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
".": "0.3.13"
".": "0.3.14"
}
32 changes: 32 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,37 @@
# Changelog

## 0.3.14 (2023-10-11)

Full Changelog: [v0.3.13...v0.3.14](https://github.com/anthropics/anthropic-sdk-python/compare/v0.3.13...v0.3.14)

### Features

* **client:** add forwards-compatible pydantic methods ([#171](https://github.com/anthropics/anthropic-sdk-python/issues/171)) ([4c5289e](https://github.com/anthropics/anthropic-sdk-python/commit/4c5289eb8519ca9a53e9483422237aa25944f8d8))
* **client:** add support for passing in a httpx client ([#173](https://github.com/anthropics/anthropic-sdk-python/issues/173)) ([25046c4](https://github.com/anthropics/anthropic-sdk-python/commit/25046c4fbc6f9d343e3b1f21024cf3982ac48c35))
* **client:** handle retry-after header with a date format ([#168](https://github.com/anthropics/anthropic-sdk-python/issues/168)) ([afeabf1](https://github.com/anthropics/anthropic-sdk-python/commit/afeabf13aa5795a7fadd141e53ec81eadbce099a))
* **client:** retry on 408 Request Timeout ([#155](https://github.com/anthropics/anthropic-sdk-python/issues/155)) ([46386f8](https://github.com/anthropics/anthropic-sdk-python/commit/46386f8f60223f45bc133ddfcfda8d9ca9da26a8))
* **package:** export a root error type ([#163](https://github.com/anthropics/anthropic-sdk-python/issues/163)) ([e7aa3e7](https://github.com/anthropics/anthropic-sdk-python/commit/e7aa3e7785ae511fa35a68ac72079a6230ca84f3))
* **types:** improve params type names ([#160](https://github.com/anthropics/anthropic-sdk-python/issues/160)) ([43544a6](https://github.com/anthropics/anthropic-sdk-python/commit/43544a62c8410061c1a50282f4c45d029db7779b))


### Bug Fixes

* **client:** don't error by default for unexpected content types ([#161](https://github.com/anthropics/anthropic-sdk-python/issues/161)) ([76cfcf9](https://github.com/anthropics/anthropic-sdk-python/commit/76cfcf91172f9804056a7d5c1ec99666ad5991a2))
* **client:** properly configure model set fields ([#154](https://github.com/anthropics/anthropic-sdk-python/issues/154)) ([da6ccb1](https://github.com/anthropics/anthropic-sdk-python/commit/da6ccb10a38e862153871a540cb75af0afdaefb3))


### Chores

* **internal:** add helpers ([#156](https://github.com/anthropics/anthropic-sdk-python/issues/156)) ([00f5a19](https://github.com/anthropics/anthropic-sdk-python/commit/00f5a19c9393f6238759faea40405e60b2054da3))
* **internal:** move error classes from _base_exceptions to _exceptions (⚠️ breaking) ([#162](https://github.com/anthropics/anthropic-sdk-python/issues/162)) ([329b307](https://github.com/anthropics/anthropic-sdk-python/commit/329b307c205435d367c0d4b29b252be807c61c68))
* **tests:** improve raw response test ([#166](https://github.com/anthropics/anthropic-sdk-python/issues/166)) ([8042473](https://github.com/anthropics/anthropic-sdk-python/commit/8042473bd73faa0b819c27a68bfc19b918361461))


### Documentation

* add some missing inline documentation ([#151](https://github.com/anthropics/anthropic-sdk-python/issues/151)) ([1f98257](https://github.com/anthropics/anthropic-sdk-python/commit/1f9825775d58ed8a62b000caaddd622ed4ba3fd2))
* update readme ([#172](https://github.com/anthropics/anthropic-sdk-python/issues/172)) ([351095b](https://github.com/anthropics/anthropic-sdk-python/commit/351095b189b111a74e9e1825ce5b6da6673a1635))

## 0.3.13 (2023-09-11)

Full Changelog: [v0.3.12...v0.3.13](https://github.com/anthropics/anthropic-sdk-python/compare/v0.3.12...v0.3.13)
Expand Down
69 changes: 44 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# Anthropic Python API Library
# Anthropic Python API library

[![PyPI version](https://img.shields.io/pypi/v/anthropic.svg)](https://pypi.org/project/anthropic/)

The Anthropic Python library provides convenient access to the Anthropic REST API from any Python 3.7+
application. It 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).

For the AWS Bedrock API, see [`anthropic-bedrock`](github.com/anthropics/anthropic-bedrock-python).

## Migration from v0.2.x and below

In `v0.3.0`, we introduced a fully rewritten SDK.
Expand Down Expand Up @@ -72,7 +74,7 @@ as v0.3 sends the `Anthropic-Version: 2023-06-01` header.

## Documentation

The API documentation can be found [here](https://docs.anthropic.com/claude/reference/).
The API documentation can be found at [https://docs.anthropic.com/claude/reference/](https://docs.anthropic.com/claude/reference/).

## Installation

Expand Down Expand Up @@ -103,7 +105,7 @@ print(completion.completion)
While you can provide an `api_key` keyword argument, we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
and adding `ANTHROPIC_API_KEY="my api key"` to your `.env` file so that your API Key is not stored in source control.

## Async Usage
## Async usage

Simply import `AsyncAnthropic` instead of `Anthropic` and use `await` with each API call:

Expand Down Expand Up @@ -166,11 +168,11 @@ async for completion in stream:
print(completion.completion, end="", flush=True)
```

## Using Types
## 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, you can call `dict(model)`.
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 `dict(model)`.

This helps 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"`.
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`.

## Token counting

Expand All @@ -183,10 +185,10 @@ client.count_tokens('Hello world!') # 3

## Handling errors

When the library is unable to connect to the API (e.g., due to network connection problems or a timeout), a subclass of `anthropic.APIConnectionError` is raised.
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `anthropic.APIConnectionError` is raised.

When the API returns a non-success status code (i.e., 4xx or 5xx
response), a subclass of `anthropic.APIStatusError` will be raised, containing `status_code` and `response` properties.
When the API returns a non-success status code (that is, 4xx or 5xx
response), a subclass of `anthropic.APIStatusError` is raised, containing `status_code` and `response` properties.

All errors inherit from `anthropic.APIError`.

Expand Down Expand Up @@ -227,11 +229,11 @@ Error codes are as followed:

### Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff.
Connection errors (for example, due to a network connectivity problem), 409 Conflict, 429 Rate Limit,
and >=500 Internal errors will all be retried by default.
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.

You can use the `max_retries` option to configure or disable this:
You can use the `max_retries` option to configure or disable retry settings:

```python
from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
Expand All @@ -252,8 +254,8 @@ anthropic.with_options(max_retries=5).completions.create(

### Timeouts

Requests time out after 10 minutes by default. 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):
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:

```python
from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
Expand All @@ -279,7 +281,7 @@ anthropic.with_options(timeout=5 * 1000).completions.create(

On timeout, an `APITimeoutError` is thrown.

Note that requests which time out will be [retried twice by default](#retries).
Note that requests that time out are [retried twice by default](#retries).

## Default Headers

Expand All @@ -297,27 +299,44 @@ client = Anthropic(
)
```

## Advanced: Configuring custom URLs, proxies, and transports
## Advanced

### 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`:

You can configure the following keyword arguments when instantiating the client:
```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}.')
```

### 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:

- Support for proxies
- Custom transports
- Additional [advanced](https://www.python-httpx.org/advanced/#client-instances) functionality

```python
import httpx
from anthropic import Anthropic

client = Anthropic(
# Use a custom base URL
base_url="http://my.test.server.example.com:8083",
proxies="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
http_client=httpx.Client(
proxies="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)
```

See the httpx documentation for information about the [`proxies`](https://www.python-httpx.org/advanced/#http-proxying) and [`transport`](https://www.python-httpx.org/advanced/#custom-transports) keyword arguments.

## Advanced: Managing HTTP resources
### Managing HTTP resources

By default we will close the underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__) is called but you can also manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
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.

## Versioning

Expand Down
4 changes: 2 additions & 2 deletions bin/check-test-server
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ function prism_is_running() {
}

function is_overriding_api_base_url() {
[ -n "$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 ${API_BASE_URL}${NC}"
echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}"

exit 0
elif prism_is_running ; then
Expand Down
2 changes: 1 addition & 1 deletion noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ def test_pydantic_v1(session: nox.Session) -> None:
# https://github.com/cjolowicz/nox-poetry/issues/1116
session._session.run("python", "-m", "pip", "install", "pydantic<2", external=True) # type: ignore

session.run("pytest", "--showlocals", "--ignore=tests/functional")
session.run("pytest", "--showlocals", "--ignore=tests/functional", *session.posargs)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "anthropic"
version = "0.3.13"
version = "0.3.14"
description = "Client library for the anthropic API"
readme = "README.md"
authors = ["Anthropic <[email protected]>"]
Expand Down
1 change: 1 addition & 0 deletions release-please-config.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"bump-minor-pre-major": true,
"bump-patch-for-minor-pre-major": true,
"pull-request-header": "Automated Release PR",
"pull-request-title-pattern": "release: ${version}",
"changelog-sections": [
{
"type": "feat",
Expand Down
19 changes: 10 additions & 9 deletions src/anthropic/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
Transport,
AsyncClient,
AsyncStream,
ProxiesTypes,
AsyncAnthropic,
RequestOptions,
)
Expand All @@ -22,6 +21,7 @@
APIError,
ConflictError,
NotFoundError,
AnthropicError,
APIStatusError,
RateLimitError,
APITimeoutError,
Expand All @@ -41,19 +41,20 @@
"NoneType",
"Transport",
"ProxiesTypes",
"AnthropicError",
"APIError",
"APIConnectionError",
"APIResponseValidationError",
"APIStatusError",
"APITimeoutError",
"AuthenticationError",
"APIConnectionError",
"APIResponseValidationError",
"BadRequestError",
"ConflictError",
"InternalServerError",
"NotFoundError",
"AuthenticationError",
"PermissionDeniedError",
"RateLimitError",
"NotFoundError",
"ConflictError",
"UnprocessableEntityError",
"RateLimitError",
"InternalServerError",
"Timeout",
"RequestOptions",
"Client",
Expand All @@ -70,7 +71,7 @@
# 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.
# anthropic._base_exceptions.NotFoundError -> anthropic.NotFoundError
# anthropic._exceptions.NotFoundError -> anthropic.NotFoundError
__locals = locals()
for __name in __all__:
if not __name.startswith("__"):
Expand Down
Loading