source: kdnuggets: getting started with the claude api in python

level: technical

you need python 3.9 or higher, a claude console account, and an api key. install the anthropic sdk with pip and store your key as an environment variable. the sdk reads it automatically, so you never hardcode it in source files. the main entry point is client.messages.create(), where you pass a model id, a max_tokens limit, and a messages list. the messages list is a list of dicts with role and content keys, and it must start with a user turn.

the response is a typed message object with fields like id, role, content, stop_reason, and usage. stop_reason tells you why claude stopped—end_turn means it finished naturally, while max_tokens means it hit your limit. usage tracks input and output tokens for billing and context monitoring. content is a list, and for text responses you access it with response.content[0].text. system prompts let you set a persistent role or constraints by passing a system parameter separate from the messages list.

for streaming, use client.messages.stream() as a context manager. iterate over stream.text_stream to get text chunks as they arrive, printing with end="" and flush=true for real-time display. the context manager ensures clean connection closure. after streaming, call stream.get_final_message() to get the full message object with token counts. this covers the basics: requests, structured responses, system prompts, and streaming, giving you a foundation for building with the claude api.

why it matters: understanding the claude api's response structure, streaming, and system prompts helps data scientists integrate large language models into applications efficiently.


source: kdnuggets: getting started with the claude api in python