llm-anthropic 0.11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.1
2
+ Name: llm-anthropic
3
+ Version: 0.11
4
+ Summary: LLM access to models by Anthropic, including the Claude series
5
+ Author: Simon Willison
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/simonw/llm-anthropic
8
+ Project-URL: Changelog, https://github.com/simonw/llm-anthropic/releases
9
+ Project-URL: Issues, https://github.com/simonw/llm-anthropic/issues
10
+ Project-URL: CI, https://github.com/simonw/llm-anthropic/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: llm>=0.19
15
+ Requires-Dist: anthropic>=0.39.0
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest; extra == "test"
18
+ Requires-Dist: pytest-recording; extra == "test"
19
+ Requires-Dist: pytest-asyncio; extra == "test"
20
+
21
+ # llm-anthropic
22
+
23
+ [![PyPI](https://img.shields.io/pypi/v/llm-anthropic.svg)](https://pypi.org/project/llm-anthropic/)
24
+ [![Changelog](https://img.shields.io/github/v/release/simonw/llm-anthropic?include_prereleases&label=changelog)](https://github.com/simonw/llm-anthropic/releases)
25
+ [![Tests](https://github.com/simonw/llm-anthropic/actions/workflows/test.yml/badge.svg)](https://github.com/simonw/llm-anthropic/actions/workflows/test.yml)
26
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/llm-anthropic/blob/main/LICENSE)
27
+
28
+ LLM access to models by Anthropic, including the Claude series
29
+
30
+ ## Installation
31
+
32
+ Install this plugin in the same environment as [LLM](https://llm.datasette.io/).
33
+ ```bash
34
+ llm install llm-anthropic
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ First, set [an API key](https://console.anthropic.com/settings/keys) for Anthropic:
40
+ ```bash
41
+ llm keys set anthropic
42
+ # Paste key here
43
+ ```
44
+
45
+ You can also set the key in the environment variable `ANTHROPIC_API_KEY`
46
+
47
+ Run `llm models` to list the models, and `llm models --options` to include a list of their options.
48
+
49
+ Run prompts like this:
50
+ ```bash
51
+ llm -m anthropic/claude-3.5-sonnet 'Fun facts about pelicans'
52
+ llm -m anthropic/claude-3.5-haiku 'Fun facts about armadillos'
53
+ llm -m anthropic/claude-3-opus 'Fun facts about squirrels'
54
+ ```
55
+ Images are supported too, for models other than Claude 3.5 Haiku:
56
+ ```bash
57
+ llm -m anthropic/claude-3.5-sonnet 'describe this image' -a https://static.simonwillison.net/static/2024/pelicans.jpg
58
+ llm -m anthropic/claude-3-haiku 'extract text' -a page.png
59
+ ```
60
+ Claude 3.5 Sonnet can handle PDF files:
61
+ ```bash
62
+ llm -m anthropic/claude-3.5-sonnet 'extract text' -a page.pdf
63
+ ```
64
+ The plugin sets up `claude-3.5-sonnet` and similar as aliases, usable like this:
65
+ ```bash
66
+ llm -m claude-3.5-sonnet 'Fun facts about pelicans'
67
+ ```
68
+
69
+ ## Development
70
+
71
+ To set up this plugin locally, first checkout the code. Then create a new virtual environment:
72
+ ```bash
73
+ cd llm-anthropic
74
+ python3 -m venv venv
75
+ source venv/bin/activate
76
+ ```
77
+ Now install the dependencies and test dependencies:
78
+ ```bash
79
+ llm install -e '.[test]'
80
+ ```
81
+ To run the tests:
82
+ ```bash
83
+ pytest
84
+ ```
85
+
86
+ This project uses [pytest-recording](https://github.com/kiwicom/pytest-recording) to record Anthropic API responses for the tests.
87
+
88
+ If you add a new test that calls the API you can capture the API response like this:
89
+ ```bash
90
+ PYTEST_ANTHROPIC_API_KEY="$(llm keys get claude)" pytest --record-mode once
91
+ ```
92
+ You will need to have stored a valid Anthropic API key using this command first:
93
+ ```bash
94
+ llm keys set claude
95
+ # Paste key here
96
+ ```
@@ -0,0 +1,76 @@
1
+ # llm-anthropic
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/llm-anthropic.svg)](https://pypi.org/project/llm-anthropic/)
4
+ [![Changelog](https://img.shields.io/github/v/release/simonw/llm-anthropic?include_prereleases&label=changelog)](https://github.com/simonw/llm-anthropic/releases)
5
+ [![Tests](https://github.com/simonw/llm-anthropic/actions/workflows/test.yml/badge.svg)](https://github.com/simonw/llm-anthropic/actions/workflows/test.yml)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/llm-anthropic/blob/main/LICENSE)
7
+
8
+ LLM access to models by Anthropic, including the Claude series
9
+
10
+ ## Installation
11
+
12
+ Install this plugin in the same environment as [LLM](https://llm.datasette.io/).
13
+ ```bash
14
+ llm install llm-anthropic
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ First, set [an API key](https://console.anthropic.com/settings/keys) for Anthropic:
20
+ ```bash
21
+ llm keys set anthropic
22
+ # Paste key here
23
+ ```
24
+
25
+ You can also set the key in the environment variable `ANTHROPIC_API_KEY`
26
+
27
+ Run `llm models` to list the models, and `llm models --options` to include a list of their options.
28
+
29
+ Run prompts like this:
30
+ ```bash
31
+ llm -m anthropic/claude-3.5-sonnet 'Fun facts about pelicans'
32
+ llm -m anthropic/claude-3.5-haiku 'Fun facts about armadillos'
33
+ llm -m anthropic/claude-3-opus 'Fun facts about squirrels'
34
+ ```
35
+ Images are supported too, for models other than Claude 3.5 Haiku:
36
+ ```bash
37
+ llm -m anthropic/claude-3.5-sonnet 'describe this image' -a https://static.simonwillison.net/static/2024/pelicans.jpg
38
+ llm -m anthropic/claude-3-haiku 'extract text' -a page.png
39
+ ```
40
+ Claude 3.5 Sonnet can handle PDF files:
41
+ ```bash
42
+ llm -m anthropic/claude-3.5-sonnet 'extract text' -a page.pdf
43
+ ```
44
+ The plugin sets up `claude-3.5-sonnet` and similar as aliases, usable like this:
45
+ ```bash
46
+ llm -m claude-3.5-sonnet 'Fun facts about pelicans'
47
+ ```
48
+
49
+ ## Development
50
+
51
+ To set up this plugin locally, first checkout the code. Then create a new virtual environment:
52
+ ```bash
53
+ cd llm-anthropic
54
+ python3 -m venv venv
55
+ source venv/bin/activate
56
+ ```
57
+ Now install the dependencies and test dependencies:
58
+ ```bash
59
+ llm install -e '.[test]'
60
+ ```
61
+ To run the tests:
62
+ ```bash
63
+ pytest
64
+ ```
65
+
66
+ This project uses [pytest-recording](https://github.com/kiwicom/pytest-recording) to record Anthropic API responses for the tests.
67
+
68
+ If you add a new test that calls the API you can capture the API response like this:
69
+ ```bash
70
+ PYTEST_ANTHROPIC_API_KEY="$(llm keys get claude)" pytest --record-mode once
71
+ ```
72
+ You will need to have stored a valid Anthropic API key using this command first:
73
+ ```bash
74
+ llm keys set claude
75
+ # Paste key here
76
+ ```
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.1
2
+ Name: llm-anthropic
3
+ Version: 0.11
4
+ Summary: LLM access to models by Anthropic, including the Claude series
5
+ Author: Simon Willison
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/simonw/llm-anthropic
8
+ Project-URL: Changelog, https://github.com/simonw/llm-anthropic/releases
9
+ Project-URL: Issues, https://github.com/simonw/llm-anthropic/issues
10
+ Project-URL: CI, https://github.com/simonw/llm-anthropic/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: llm>=0.19
15
+ Requires-Dist: anthropic>=0.39.0
16
+ Provides-Extra: test
17
+ Requires-Dist: pytest; extra == "test"
18
+ Requires-Dist: pytest-recording; extra == "test"
19
+ Requires-Dist: pytest-asyncio; extra == "test"
20
+
21
+ # llm-anthropic
22
+
23
+ [![PyPI](https://img.shields.io/pypi/v/llm-anthropic.svg)](https://pypi.org/project/llm-anthropic/)
24
+ [![Changelog](https://img.shields.io/github/v/release/simonw/llm-anthropic?include_prereleases&label=changelog)](https://github.com/simonw/llm-anthropic/releases)
25
+ [![Tests](https://github.com/simonw/llm-anthropic/actions/workflows/test.yml/badge.svg)](https://github.com/simonw/llm-anthropic/actions/workflows/test.yml)
26
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/llm-anthropic/blob/main/LICENSE)
27
+
28
+ LLM access to models by Anthropic, including the Claude series
29
+
30
+ ## Installation
31
+
32
+ Install this plugin in the same environment as [LLM](https://llm.datasette.io/).
33
+ ```bash
34
+ llm install llm-anthropic
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ First, set [an API key](https://console.anthropic.com/settings/keys) for Anthropic:
40
+ ```bash
41
+ llm keys set anthropic
42
+ # Paste key here
43
+ ```
44
+
45
+ You can also set the key in the environment variable `ANTHROPIC_API_KEY`
46
+
47
+ Run `llm models` to list the models, and `llm models --options` to include a list of their options.
48
+
49
+ Run prompts like this:
50
+ ```bash
51
+ llm -m anthropic/claude-3.5-sonnet 'Fun facts about pelicans'
52
+ llm -m anthropic/claude-3.5-haiku 'Fun facts about armadillos'
53
+ llm -m anthropic/claude-3-opus 'Fun facts about squirrels'
54
+ ```
55
+ Images are supported too, for models other than Claude 3.5 Haiku:
56
+ ```bash
57
+ llm -m anthropic/claude-3.5-sonnet 'describe this image' -a https://static.simonwillison.net/static/2024/pelicans.jpg
58
+ llm -m anthropic/claude-3-haiku 'extract text' -a page.png
59
+ ```
60
+ Claude 3.5 Sonnet can handle PDF files:
61
+ ```bash
62
+ llm -m anthropic/claude-3.5-sonnet 'extract text' -a page.pdf
63
+ ```
64
+ The plugin sets up `claude-3.5-sonnet` and similar as aliases, usable like this:
65
+ ```bash
66
+ llm -m claude-3.5-sonnet 'Fun facts about pelicans'
67
+ ```
68
+
69
+ ## Development
70
+
71
+ To set up this plugin locally, first checkout the code. Then create a new virtual environment:
72
+ ```bash
73
+ cd llm-anthropic
74
+ python3 -m venv venv
75
+ source venv/bin/activate
76
+ ```
77
+ Now install the dependencies and test dependencies:
78
+ ```bash
79
+ llm install -e '.[test]'
80
+ ```
81
+ To run the tests:
82
+ ```bash
83
+ pytest
84
+ ```
85
+
86
+ This project uses [pytest-recording](https://github.com/kiwicom/pytest-recording) to record Anthropic API responses for the tests.
87
+
88
+ If you add a new test that calls the API you can capture the API response like this:
89
+ ```bash
90
+ PYTEST_ANTHROPIC_API_KEY="$(llm keys get claude)" pytest --record-mode once
91
+ ```
92
+ You will need to have stored a valid Anthropic API key using this command first:
93
+ ```bash
94
+ llm keys set claude
95
+ # Paste key here
96
+ ```
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ llm_anthropic.py
4
+ pyproject.toml
5
+ llm_anthropic.egg-info/PKG-INFO
6
+ llm_anthropic.egg-info/SOURCES.txt
7
+ llm_anthropic.egg-info/dependency_links.txt
8
+ llm_anthropic.egg-info/entry_points.txt
9
+ llm_anthropic.egg-info/requires.txt
10
+ llm_anthropic.egg-info/top_level.txt
11
+ tests/test_claude_3.py
@@ -0,0 +1,2 @@
1
+ [llm]
2
+ anthropic = llm_anthropic
@@ -0,0 +1,7 @@
1
+ llm>=0.19
2
+ anthropic>=0.39.0
3
+
4
+ [test]
5
+ pytest
6
+ pytest-recording
7
+ pytest-asyncio
@@ -0,0 +1 @@
1
+ llm_anthropic
@@ -0,0 +1,280 @@
1
+ from anthropic import Anthropic, AsyncAnthropic
2
+ import llm
3
+ from pydantic import Field, field_validator, model_validator
4
+ from typing import Optional, List
5
+
6
+
7
+ @llm.hookimpl
8
+ def register_models(register):
9
+ # https://docs.anthropic.com/claude/docs/models-overview
10
+ register(
11
+ ClaudeMessages("claude-3-opus-20240229"),
12
+ AsyncClaudeMessages("claude-3-opus-20240229"),
13
+ ),
14
+ register(
15
+ ClaudeMessages("claude-3-opus-latest"),
16
+ AsyncClaudeMessages("claude-3-opus-latest"),
17
+ aliases=("claude-3-opus",),
18
+ )
19
+ register(
20
+ ClaudeMessages("claude-3-sonnet-20240229"),
21
+ AsyncClaudeMessages("claude-3-sonnet-20240229"),
22
+ aliases=("claude-3-sonnet",),
23
+ )
24
+ register(
25
+ ClaudeMessages("claude-3-haiku-20240307"),
26
+ AsyncClaudeMessages("claude-3-haiku-20240307"),
27
+ aliases=("claude-3-haiku",),
28
+ )
29
+ # 3.5 models
30
+ register(
31
+ ClaudeMessagesLong("claude-3-5-sonnet-20240620", supports_pdf=True),
32
+ AsyncClaudeMessagesLong("claude-3-5-sonnet-20240620", supports_pdf=True),
33
+ )
34
+ register(
35
+ ClaudeMessagesLong("claude-3-5-sonnet-20241022", supports_pdf=True),
36
+ AsyncClaudeMessagesLong("claude-3-5-sonnet-20241022", supports_pdf=True),
37
+ )
38
+ register(
39
+ ClaudeMessagesLong("claude-3-5-sonnet-latest", supports_pdf=True),
40
+ AsyncClaudeMessagesLong("claude-3-5-sonnet-latest", supports_pdf=True),
41
+ aliases=("claude-3.5-sonnet", "claude-3.5-sonnet-latest"),
42
+ )
43
+ register(
44
+ ClaudeMessagesLong("claude-3-5-haiku-latest", supports_images=False),
45
+ AsyncClaudeMessagesLong("claude-3-5-haiku-latest", supports_images=False),
46
+ aliases=("claude-3.5-haiku",),
47
+ )
48
+
49
+
50
+ class ClaudeOptions(llm.Options):
51
+ max_tokens: Optional[int] = Field(
52
+ description="The maximum number of tokens to generate before stopping",
53
+ default=4_096,
54
+ )
55
+
56
+ temperature: Optional[float] = Field(
57
+ description="Amount of randomness injected into the response. Defaults to 1.0. Ranges from 0.0 to 1.0. Use temperature closer to 0.0 for analytical / multiple choice, and closer to 1.0 for creative and generative tasks. Note that even with temperature of 0.0, the results will not be fully deterministic.",
58
+ default=1.0,
59
+ )
60
+
61
+ top_p: Optional[float] = Field(
62
+ description="Use nucleus sampling. In nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by top_p. You should either alter temperature or top_p, but not both. Recommended for advanced use cases only. You usually only need to use temperature.",
63
+ default=None,
64
+ )
65
+
66
+ top_k: Optional[int] = Field(
67
+ description="Only sample from the top K options for each subsequent token. Used to remove 'long tail' low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.",
68
+ default=None,
69
+ )
70
+
71
+ user_id: Optional[str] = Field(
72
+ description="An external identifier for the user who is associated with the request",
73
+ default=None,
74
+ )
75
+
76
+ @field_validator("max_tokens")
77
+ @classmethod
78
+ def validate_max_tokens(cls, max_tokens):
79
+ real_max = cls.model_fields["max_tokens"].default
80
+ if not (0 < max_tokens <= real_max):
81
+ raise ValueError("max_tokens must be in range 1-{}".format(real_max))
82
+ return max_tokens
83
+
84
+ @field_validator("temperature")
85
+ @classmethod
86
+ def validate_temperature(cls, temperature):
87
+ if not (0.0 <= temperature <= 1.0):
88
+ raise ValueError("temperature must be in range 0.0-1.0")
89
+ return temperature
90
+
91
+ @field_validator("top_p")
92
+ @classmethod
93
+ def validate_top_p(cls, top_p):
94
+ if top_p is not None and not (0.0 <= top_p <= 1.0):
95
+ raise ValueError("top_p must be in range 0.0-1.0")
96
+ return top_p
97
+
98
+ @field_validator("top_k")
99
+ @classmethod
100
+ def validate_top_k(cls, top_k):
101
+ if top_k is not None and top_k <= 0:
102
+ raise ValueError("top_k must be a positive integer")
103
+ return top_k
104
+
105
+ @model_validator(mode="after")
106
+ def validate_temperature_top_p(self):
107
+ if self.temperature != 1.0 and self.top_p is not None:
108
+ raise ValueError("Only one of temperature and top_p can be set")
109
+ return self
110
+
111
+
112
+ long_field = Field(
113
+ description="The maximum number of tokens to generate before stopping",
114
+ default=4_096 * 2,
115
+ )
116
+
117
+
118
+ class _Shared:
119
+ needs_key = "anthropic"
120
+ key_env_var = "ANTHROPIC_API_KEY"
121
+ can_stream = True
122
+
123
+ class Options(ClaudeOptions): ...
124
+
125
+ def __init__(
126
+ self,
127
+ model_id,
128
+ claude_model_id=None,
129
+ supports_images=True,
130
+ supports_pdf=False,
131
+ ):
132
+ self.model_id = 'anthropic/' + model_id
133
+ self.claude_model_id = claude_model_id or model_id
134
+ self.attachment_types = set()
135
+ if supports_images:
136
+ self.attachment_types.update(
137
+ {
138
+ "image/png",
139
+ "image/jpeg",
140
+ "image/webp",
141
+ "image/gif",
142
+ }
143
+ )
144
+ if supports_pdf:
145
+ self.attachment_types.add("application/pdf")
146
+
147
+ def build_messages(self, prompt, conversation) -> List[dict]:
148
+ messages = []
149
+ if conversation:
150
+ for response in conversation.responses:
151
+ if response.attachments:
152
+ content = [
153
+ {
154
+ "type": (
155
+ "document"
156
+ if attachment.resolve_type() == "application/pdf"
157
+ else "image"
158
+ ),
159
+ "source": {
160
+ "data": attachment.base64_content(),
161
+ "media_type": attachment.resolve_type(),
162
+ "type": "base64",
163
+ },
164
+ }
165
+ for attachment in response.attachments
166
+ ]
167
+ content.append({"type": "text", "text": response.prompt.prompt})
168
+ else:
169
+ content = response.prompt.prompt
170
+ messages.extend(
171
+ [
172
+ {
173
+ "role": "user",
174
+ "content": content,
175
+ },
176
+ {"role": "assistant", "content": response.text()},
177
+ ]
178
+ )
179
+ if prompt.attachments:
180
+ content = [
181
+ {
182
+ "type": (
183
+ "document"
184
+ if attachment.resolve_type() == "application/pdf"
185
+ else "image"
186
+ ),
187
+ "source": {
188
+ "data": attachment.base64_content(),
189
+ "media_type": attachment.resolve_type(),
190
+ "type": "base64",
191
+ },
192
+ }
193
+ for attachment in prompt.attachments
194
+ ]
195
+ content.append({"type": "text", "text": prompt.prompt})
196
+ messages.append(
197
+ {
198
+ "role": "user",
199
+ "content": content,
200
+ }
201
+ )
202
+ else:
203
+ messages.append({"role": "user", "content": prompt.prompt})
204
+ return messages
205
+
206
+ def build_kwargs(self, prompt, conversation):
207
+ kwargs = {
208
+ "model": self.claude_model_id,
209
+ "messages": self.build_messages(prompt, conversation),
210
+ "max_tokens": prompt.options.max_tokens,
211
+ }
212
+ if prompt.options.user_id:
213
+ kwargs["metadata"] = {"user_id": prompt.options.user_id}
214
+
215
+ if prompt.options.top_p:
216
+ kwargs["top_p"] = prompt.options.top_p
217
+ else:
218
+ kwargs["temperature"] = prompt.options.temperature
219
+
220
+ if prompt.options.top_k:
221
+ kwargs["top_k"] = prompt.options.top_k
222
+
223
+ if prompt.system:
224
+ kwargs["system"] = prompt.system
225
+
226
+ return kwargs
227
+
228
+ def set_usage(self, response):
229
+ usage = response.response_json.pop("usage")
230
+ if usage:
231
+ response.set_usage(
232
+ input=usage.get("input_tokens"), output=usage.get("output_tokens")
233
+ )
234
+
235
+ def __str__(self):
236
+ return "Anthropic Messages: {}".format(self.model_id)
237
+
238
+
239
+ class ClaudeMessages(_Shared, llm.Model):
240
+
241
+ def execute(self, prompt, stream, response, conversation):
242
+ client = Anthropic(api_key=self.get_key())
243
+ kwargs = self.build_kwargs(prompt, conversation)
244
+ if stream:
245
+ with client.messages.stream(**kwargs) as stream:
246
+ for text in stream.text_stream:
247
+ yield text
248
+ # This records usage and other data:
249
+ response.response_json = stream.get_final_message().model_dump()
250
+ else:
251
+ completion = client.messages.create(**kwargs)
252
+ yield completion.content[0].text
253
+ response.response_json = completion.model_dump()
254
+ self.set_usage(response)
255
+
256
+
257
+ class ClaudeMessagesLong(ClaudeMessages):
258
+ class Options(ClaudeOptions):
259
+ max_tokens: Optional[int] = long_field
260
+
261
+
262
+ class AsyncClaudeMessages(_Shared, llm.AsyncModel):
263
+ async def execute(self, prompt, stream, response, conversation):
264
+ client = AsyncAnthropic(api_key=self.get_key())
265
+ kwargs = self.build_kwargs(prompt, conversation)
266
+ if stream:
267
+ async with client.messages.stream(**kwargs) as stream_obj:
268
+ async for text in stream_obj.text_stream:
269
+ yield text
270
+ response.response_json = (await stream_obj.get_final_message()).model_dump()
271
+ else:
272
+ completion = await client.messages.create(**kwargs)
273
+ yield completion.content[0].text
274
+ response.response_json = completion.model_dump()
275
+ self.set_usage(response)
276
+
277
+
278
+ class AsyncClaudeMessagesLong(AsyncClaudeMessages):
279
+ class Options(ClaudeOptions):
280
+ max_tokens: Optional[int] = long_field
@@ -0,0 +1,26 @@
1
+ [project]
2
+ name = "llm-anthropic"
3
+ version = "0.11"
4
+ description = "LLM access to models by Anthropic, including the Claude series"
5
+ readme = "README.md"
6
+ authors = [{name = "Simon Willison"}]
7
+ license = {text = "Apache-2.0"}
8
+ classifiers = [
9
+ "License :: OSI Approved :: Apache Software License"
10
+ ]
11
+ dependencies = [
12
+ "llm>=0.19",
13
+ "anthropic>=0.39.0",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/simonw/llm-anthropic"
18
+ Changelog = "https://github.com/simonw/llm-anthropic/releases"
19
+ Issues = "https://github.com/simonw/llm-anthropic/issues"
20
+ CI = "https://github.com/simonw/llm-anthropic/actions"
21
+
22
+ [project.entry-points.llm]
23
+ anthropic = "llm_anthropic"
24
+
25
+ [project.optional-dependencies]
26
+ test = ["pytest", "pytest-recording", "pytest-asyncio"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,96 @@
1
+ import llm
2
+ import os
3
+ import pytest
4
+
5
+ TINY_PNG = (
6
+ b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\xa6\x00\x00\x01\x1a"
7
+ b"\x02\x03\x00\x00\x00\xe6\x99\xc4^\x00\x00\x00\tPLTE\xff\xff\xff"
8
+ b"\x00\xff\x00\xfe\x01\x00\x12t\x01J\x00\x00\x00GIDATx\xda\xed\xd81\x11"
9
+ b"\x000\x08\xc0\xc0.]\xea\xaf&Q\x89\x04V\xe0>\xf3+\xc8\x91Z\xf4\xa2\x08EQ\x14E"
10
+ b"Q\x14EQ\x14EQ\xd4B\x91$I3\xbb\xbf\x08EQ\x14EQ\x14EQ\x14E\xd1\xa5"
11
+ b"\xd4\x17\x91\xc6\x95\x05\x15\x0f\x9f\xc5\t\x9f\xa4\x00\x00\x00\x00IEND\xaeB`"
12
+ b"\x82"
13
+ )
14
+
15
+ ANTHROPIC_API_KEY = os.environ.get("PYTEST_ANTHROPIC_API_KEY", None) or "sk-..."
16
+
17
+
18
+ @pytest.mark.vcr
19
+ def test_prompt():
20
+ model = llm.get_model("claude-3-opus")
21
+ model.key = model.key or ANTHROPIC_API_KEY
22
+ response = model.prompt("Two names for a pet pelican, be brief")
23
+ assert str(response) == "1. Pelly\n2. Beaky"
24
+ response_dict = dict(response.response_json)
25
+ response_dict.pop("id") # differs between requests
26
+ assert response_dict == {
27
+ "content": [{"text": "1. Pelly\n2. Beaky", "type": "text"}],
28
+ "model": "claude-3-opus-20240229",
29
+ "role": "assistant",
30
+ "stop_reason": "end_turn",
31
+ "stop_sequence": None,
32
+ "type": "message",
33
+ }
34
+ assert response.input_tokens == 17
35
+ assert response.output_tokens == 15
36
+ assert response.token_details is None
37
+
38
+
39
+ @pytest.mark.vcr
40
+ @pytest.mark.asyncio
41
+ async def test_async_prompt():
42
+ model = llm.get_async_model("claude-3-opus")
43
+ model.key = model.key or ANTHROPIC_API_KEY # don't override existing key
44
+ response = await model.prompt("Two names for a pet pelican, be brief")
45
+ assert await response.text() == "1. Pelly\n2. Beaky"
46
+ response_dict = dict(response.response_json)
47
+ response_dict.pop("id") # differs between requests
48
+ assert response_dict == {
49
+ "content": [{"text": "1. Pelly\n2. Beaky", "type": "text"}],
50
+ "model": "claude-3-opus-20240229",
51
+ "role": "assistant",
52
+ "stop_reason": "end_turn",
53
+ "stop_sequence": None,
54
+ "type": "message",
55
+ }
56
+ assert response.input_tokens == 17
57
+ assert response.output_tokens == 15
58
+ assert response.token_details is None
59
+
60
+
61
+ EXPECTED_IMAGE_TEXT = (
62
+ "This image shows two simple rectangular blocks of solid colors stacked "
63
+ "vertically. The top rectangle is a bright, vibrant red color, while the "
64
+ "bottom rectangle is a bright, neon green color. The rectangles appear to "
65
+ "be of similar width but may be slightly different in height. The colors "
66
+ "are very saturated and create a striking contrast against each other."
67
+ )
68
+
69
+
70
+ @pytest.mark.vcr
71
+ def test_image_prompt():
72
+ model = llm.get_model("claude-3.5-sonnet")
73
+ model.key = model.key or ANTHROPIC_API_KEY
74
+ response = model.prompt(
75
+ "Describe image in three words",
76
+ attachments=[llm.Attachment(content=TINY_PNG)],
77
+ )
78
+ assert str(response) == EXPECTED_IMAGE_TEXT
79
+ response_dict = response.response_json
80
+ response_dict.pop("id") # differs between requests
81
+ assert response_dict == {
82
+ "content": [
83
+ {
84
+ "text": EXPECTED_IMAGE_TEXT,
85
+ "type": "text",
86
+ }
87
+ ],
88
+ "model": "claude-3-5-sonnet-20241022",
89
+ "role": "assistant",
90
+ "stop_reason": "end_turn",
91
+ "stop_sequence": None,
92
+ "type": "message",
93
+ }
94
+ assert response.input_tokens == 76
95
+ assert response.output_tokens == 75
96
+ assert response.token_details is None