In questo esempio, faremo scrivere a Claude una funzione Python che verifica se una stringa è un palindromo.

Prerequisiti

Avrai bisogno di:

Anthropic fornisce SDK per Python e TypeScript, anche se puoi effettuare richieste HTTP dirette all’API.

Inizia con la Workbench

Qualsiasi chiamata API che effettui—indipendentemente dal compito specifico—invia un prompt ben configurato all’API di Anthropic. Mentre impari a sfruttare al meglio Claude, ti consigliamo di iniziare il processo di sviluppo nella Workbench, un’interfaccia web per Claude.

Accedi alla Console Anthropic e clicca su Write a prompt from scratch.

Nella sezione centrale, sotto User, poniamo una domanda a Claude.

Why is the ocean salty?

Clicca su Run. Sul lato destro, vedrai un output simile a

Response
The ocean is salty due to several factors:

1. Weathering of rocks: Over millions of years, rain, rivers, and streams have eroded rocks containing mineral salts. These salts are carried into the ocean by water runoff.
2. Volcanic activity: Underwater volcanoes and hydrothermal vents release minerals, including salts, into the ocean water.
3. Atmospheric deposition: Salt particles from ocean spray can be carried by wind and deposited back into the ocean.
4. Evaporation: As water evaporates from the surface of the ocean, it leaves behind dissolved salts, increasing the concentration of salt in the remaining water.
5. Biological processes: Some marine organisms contribute to the ocean's salinity by releasing salt compounds as byproducts of their metabolism.

Over time, these processes have continuously added salts to the ocean, while evaporation removes pure water, leading to the ocean's current salinity levels. It's important to note that the total amount of salt in the ocean remains relatively stable because the input of salts is balanced by the removal of salts through processes like the formation of evaporite deposits.

Questa è una buona risposta, ma supponiamo di voler controllare il tipo esatto di risposta che Claude fornisce. Ad esempio, permettendo a Claude di rispondere alle domande solo con poesie. Possiamo controllare il formato, il tono e la personalità della risposta aggiungendo un System Prompt.

You are a world-class poet. Respond only with short poems.

Clicca nuovamente su Run.

Response
The ocean's salty brine,
A tale of time and elements combined.
Rocks and rain, a slow erosion,
Minerals carried in solution.
Eons pass, the salt remains,
In the vast, eternal watery domain.

Vedi come è cambiata la risposta di Claude? I modelli LLM rispondono bene a istruzioni chiare e dirette. Puoi inserire le istruzioni sul ruolo sia nel prompt di sistema che nel messaggio dell’utente. Ti consigliamo di testare per vedere quale metodo produce i migliori risultati per il tuo caso d’uso.

Una volta che hai modificato gli input in modo da essere soddisfatto dell’output e hai una buona idea di come usare Claude, converti la tua Workbench in un’integrazione.

Clicca su Get Code per copiare il codice generato che rappresenta la tua sessione Workbench.

Installa l’SDK

Anthropic fornisce SDK per Python (3.7+), TypeScript (4.5+) e Java (8+). Abbiamo anche un SDK Go attualmente in beta.

Nella directory del tuo progetto, crea un ambiente virtuale.

python -m venv claude-env

Attiva l’ambiente virtuale usando

  • Su macOS o Linux, source claude-env/bin/activate
  • Su Windows, claude-env\Scripts\activate
pip install anthropic

Imposta la tua chiave API

Ogni chiamata API richiede una chiave API valida. Gli SDK sono progettati per prendere la chiave API dalla variabile d’ambiente ANTHROPIC_API_KEY. Puoi anche fornire la chiave al client Anthropic durante l’inizializzazione.

export ANTHROPIC_API_KEY='your-api-key-here'

Chiama l’API

Chiama l’API passando i parametri corretti all’endpoint /messages.

Nota che il codice fornito dalla Workbench imposta la chiave API nel costruttore. Se hai impostato la chiave API come variabile d’ambiente, puoi omettere quella riga come mostrato di seguito.

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1000,
    temperature=1,
    system="You are a world-class poet. Respond only with short poems.",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Why is the ocean salty?"
                }
            ]
        }
    ]
)
print(message.content)

Esegui il codice usando python3 claude_quickstart.py o node claude_quickstart.js.

[TextBlock(text="The ocean's salty brine,\nA tale of time and design.\nRocks and rivers, their minerals shed,\nAccumulating in the ocean's bed.\nEvaporation leaves salt behind,\nIn the vast waters, forever enshrined.", type='text')]
La Workbench e gli esempi di codice utilizzano le impostazioni predefinite del modello per: modello (nome), temperatura e numero massimo di token da campionare.

Questa guida rapida mostra come sviluppare un’applicazione basica, ma funzionale, alimentata da Claude utilizzando la Console, la Workbench e l’API. Puoi utilizzare questo stesso flusso di lavoro come base per casi d’uso molto più potenti.

Prossimi passi

Ora che hai effettuato la tua prima richiesta all’API di Anthropic, è il momento di esplorare cos’altro è possibile: