We use cookies to enhance your experience on the site
CodeWorlds

API Integration - Connecting with AI

Now you will learn how to connect to language model APIs!

OpenAI API

Installation

1pip install openai

Basic Usage

1from openai import OpenAI
2
3# Initialize the client
4client = OpenAI(api_key="your-api-key")
5# Or set the OPENAI_API_KEY environment variable
6
7# Simple chat
8response = client.chat.completions.create(
9    model="gpt-5",
10    messages=[
11        {"role": "system", "content": "You are a Safari expert."},
12        {"role": "user", "content": "Tell me about African lions."}
13    ],
14    temperature=0.7,
15    max_tokens=500
16)
17
18# Extract the response
19answer = response.choices[0].message.content
20print(answer)

Streaming

1# Streaming - response appears in real time
2stream = client.chat.completions.create(
3    model="gpt-5",
4    messages=[{"role": "user", "content": "Write a story about Safari"}],
5    stream=True
6)
7
8for chunk in stream:
9    content = chunk.choices[0].delta.content
10    if content:
11        print(content, end="", flush=True)

Anthropic Claude API

Installation

1pip install anthropic

Basic Usage

1import anthropic
2
3# Initialize the client
4client = anthropic.Anthropic(api_key="your-api-key")
5
6# Simple chat
7message = client.messages.create(
8    model="claude-sonnet-4-6",
9    max_tokens=1024,
10    system="You are a Python programming expert.",
11    messages=[
12        {"role": "user", "content": "How do I write a sorting function?"}
13    ]
14)
15
16print(message.content[0].text)

Streaming Claude

1with client.messages.stream(
2    model="claude-sonnet-4-6",
3    max_tokens=1024,
4    messages=[{"role": "user", "content": "Write a poem about Safari"}]
5) as stream:
6    for text in stream.text_stream:
7        print(text, end="", flush=True)

Asynchronous API

1import asyncio
2from openai import AsyncOpenAI
3
4async def chat_async():
5    client = AsyncOpenAI()
6
7    response = await client.chat.completions.create(
8        model="gpt-5",
9        messages=[{"role": "user", "content": "Hello!"}]
10    )
11
12    return response.choices[0].message.content
13
14# Run
15result = asyncio.run(chat_async())

Error Handling

1from openai import OpenAI, APIError, RateLimitError
2
3client = OpenAI()
4
5try:
6    response = client.chat.completions.create(
7        model="gpt-5",
8        messages=[{"role": "user", "content": "Hello"}]
9    )
10except RateLimitError:
11    print("Rate limit - wait and try again")
12except APIError as e:
13    print(f"API Error: {e}")
Go to CodeWorlds