Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How to use Anthropic Python Package


How to use Anthropic Python Package


To use the Anthropic Python package, follow these steps:

1. Install the package using pip:

bash
pip install anthropic

2. Import the necessary modules and create an Anthropic client instance with your API key:

python
import anthropic

client = anthropic.Anthropic(api_key="your_api_key_here")

You can set the `ANTHROPIC_API_KEY` environment variable instead of passing the key directly[1].

3. Create a message with the desired parameters, such as the model, max tokens, and prompt:

python
message = client.messages.create(
    model="claude-3-5-sonnet-20240620",
    max_tokens=1000,
    messages=[
        {"role": "user", "content": "Hello, Claude"}
    ]
)

4. Print the generated response:

python
print(message.content)

Here's a complete example:

python
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-3-5-sonnet-20240620",
    max_tokens=1000,
    messages=[
        {"role": "user", "content": "Hello, Claude"}
    ]
)

print(message.content)

This will output Claude's response to the "Hello, Claude" prompt[1].

The Anthropic Python package provides convenient access to the Anthropic API from any Python 3.7+ application. It includes type definitions for all request parameters and response fields, and offers both synchronous and asynchronous clients powered by httpx[2].

For more advanced usage, you can configure custom URLs, proxies, and transports when instantiating the client[2]. The package also supports managing HTTP resources and versioning[2].

Citations:
[1] https://docs.anthropic.com/en/docs/quickstart
[2] https://pypi.org/project/anthropic/0.3.9/
[3] https://docs.anthropic.com/en/api/client-sdks
[4] https://pypi.org/project/anthropic/0.2.8/
[5] https://www.datacamp.com/tutorial/getting-started-with-the-claude-2-and-the-claude-2-api