Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Python code to show using Claude Sonnet API


Python code to show using Claude Sonnet API


Here is a Python code example to demonstrate how to use the Claude 3.5 Sonnet API:

python
import anthropic

# Set up the API client
client = anthropic.Anthropic(
    api_key="your_api_key",
    # defaults to os.environ.get("ANTHROPIC_API_KEY")
)

# Define the request parameters
model = "claude-3-5-sonnet-20240620"
max_tokens = 1000
temperature = 0.0
system = "Respond only in Yoda-speak."
messages = [
    {"role": "user", "content": "How are you today?"}
]

# Create the message
message = client.messages.create(
    model=model,
    max_tokens=max_tokens,
    temperature=temperature,
    system=system,
    messages=messages
)

# Print the response
print(message.content)

Explanation of the Code

1. Importing the `anthropic` Library:
- The `anthropic` library is imported to interact with the Claude 3.5 Sonnet API.

2. Setting Up the API Client:
- An instance of `Anthropic` is created with your API key. This key is required for accessing the API.

3. Defining Request Parameters:
- The `model` parameter specifies the model to use, which in this case is `claude-3-5-sonnet-20240620`.
- `max_tokens` sets the maximum number of tokens to generate.
- `temperature` controls the randomness of the generated text.
- `system` sets the prompt for the model.
- `messages` defines the input messages for the model.

4. Creating the Message:
- The `messages.create` method is used to create a message with the specified parameters.

5. Printing the Response:
- The response from the API is printed to the console.

Running the Code

1. Install the `anthropic` Library:
- Run `pip install anthropic` in your terminal to install the `anthropic` library.

2. Replace `your_api_key`:
- Replace `your_api_key` with your actual API key.

3. Run the Script:
- Save the code in a file, for example, `claude3.py`.
- Run the script using Python: `python claude3.py`.

This code demonstrates how to use the Claude 3.5 Sonnet API to generate text based on a prompt. You can modify the parameters to suit your specific needs.

Citations:
[1] https://github.com/topics/claude-sonnet
[2] https://beebom.com/how-access-claude-3-api-opus-sonnet-models-examples/
[3] https://apidog.com/blog/claude-3-5-api/
[4] https://openrouter.ai/models/anthropic/claude-3.5-sonnet
[5] https://github.com/topics/claude-3-sonnet