Skip to content
Visual explainer 3h to learn 4 steps

Chat APIs & official SDKs

Send multi-turn chat requests with system prompts using a provider's official Python SDK.

By Invicly Tech, , in AI Engineering with Python. About 11 minutes to read.

Topic 4 of 33

In short

Chat APIs take a list of messages with roles and return the model's reply. The official SDK handles authentication and HTTP details; your app keeps the conversation history and resends it each turn.

Explained simply

A chat API is a web address that takes a list of messages and sends back the model's reply. You could call it with plain HTTP, but every provider offers an official SDK (software development kit): a Python package that handles the web request, the login and the error details for you.

Each message has a role. The system prompt sets the rules, such as "You are a polite support agent. Answer in two sentences." User messages are what the person typed. Assistant messages are what the model said earlier. Together they form the conversation the model reads.

The API remembers nothing between calls. To have a conversation, your app keeps the list of messages and sends the whole list every time, adding the newest question at the end. If you only send the last question, the model has no idea what came before.

Your API key is like a password linked to your bill. Anyone who has it can spend your money. Keep it in an environment variable or a secret store, never in your code, and never in Git.

Press Play on a diagram to walk through it one step at a time.

SequenceA multi-turn chat
Your app
Provider SDK
LLM API
  1. 1System prompt plus user message
    Your app to Provider SDK: System prompt plus user message
  2. 2HTTPS request with API key
    Provider SDK to LLM API: HTTPS request with API key
  3. 3Assistant reply and token usage
    LLM API to Provider SDK: Assistant reply and token usage
  4. 4Response object
    Provider SDK to Your app: Response object
  5. 5Append reply to history
    Your app to Your app: Append reply to history
  6. 6Send full history plus next message
    Your app to Provider SDK: Send full history plus next message
MapOne chat API call
Chat API call
  • Request: model
    • Exact version you tested
  • Request: instructions
    • System prompt
    • Rules and output format
  • Request: messages
    • user and assistant turns
    • Newest question last
  • Request: settings
    • Max output tokens
    • Temperature
    • Stop sequences
  • Response
    • Reply content
    • Stop reason
    • Token usage
    • Request ID

In depth

What the SDK does between your code and the model

Install the SDK inside a virtual environment with pip, and pin the version in your requirements file so an upgrade cannot change behaviour by surprise. The SDK builds the HTTPS request, adds your API key as a header, turns your Python objects into JSON, and turns the JSON reply into typed response objects. Most official SDKs also add timeouts and a small number of automatic retries, and offer both a normal and an async client.

Many SDKs read the key from a provider-specific environment variable automatically if you do not pass one. In development, a .env file loaded with python-dotenv is convenient; add .env to .gitignore before creating it. In production, use your platform's secret store. Use separate keys for development and production so you can revoke one without breaking the other.

LayersFrom your code to the model
  1. 1
    Your app code

    Builds messages, reads the reply

  2. 2
    Provider SDK

    Objects to JSON, retries, timeouts

  3. 3
    HTTPS request

    API key sent in a header

  4. 4
    Provider API gateway

    Checks key, rate limits, routes

  5. 5
    Model servers

    Run the model and count tokens

Anatomy of a request and a response

A request names the model and carries the messages. Common settings are the maximum number of output tokens, temperature, and stop sequences (text that ends the reply early). Some APIs take the system prompt as its own field; others take it as the first message with a system role. Check which shape your SDK uses.

The response holds the reply content, a stop or finish reason, and a usage section with input and output token counts. Always check the stop reason. If it says the reply hit the token limit (the name differs by provider, such as length or max_tokens), the answer was cut off mid-sentence, and showing it as complete is a bug.

Log the model name, token usage and a request ID with every call. Provider support teams ask for the request ID when you report a problem.

  • Request: model, messages, max output tokens, temperature
  • Response: content, stop reason, usage
  • Hit the token limit? The reply is incomplete
  • Pin the exact model version you tested

Writing the system prompt

The system prompt is where stable rules go: who the assistant is, who it serves, what it must never do, and the format of its answers. Models give it more weight than user messages, which makes it the right place for rules the user should not be able to override.

It is not a secret, though. Users can often get a model to repeat its system prompt, so never put API keys, internal URLs or private data in it. Keep it focused: a short, clear system prompt beats a long list of rules that contradict each other.

Put things that change per request, such as the user's name or retrieved documents, in the user message or a clearly marked section, so the stable part stays identical across calls. That also helps prompt caching later.

Managing conversation history

Messages normally alternate user, assistant, user, assistant, and many APIs require the list to start with a user message. Each turn resends everything, so turn 20 sends all 19 earlier exchanges. Total tokens across a conversation therefore grow roughly with the square of its length, and long chats eventually overflow the context window.

Three strategies keep history under control. Keep only the last N messages: simple, but the model forgets early facts. Summarise older turns into a short note that you keep at the top: keeps key facts, costs an extra call now and then. Store all turns and retrieve only those related to the new question: best memory, most work.

Whatever you choose, count tokens before sending and leave room for the reply.

CompareWays to trim chat history
Last N messages
  • Easiest to build
  • Predictable token cost
  • Forgets early details
Summarise old turns
  • Keeps key facts
  • Extra model call sometimes
  • Summary can lose nuance
Retrieve relevant turns
  • Best long-term memory
  • Needs embeddings and storage
  • Most moving parts

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Install a provider SDK and set API keys~45m
  2. 2
    Send a single-turn request~45m
  3. 3
    Add a system prompt~45m
  4. 4
    Build a multi-turn conversation~45m

Key points

  • Load API keys from environment variables, never hard-code them.
  • The system prompt sets behaviour; user and assistant messages carry the conversation.
  • APIs are stateless, so send the relevant history with every request.
  • Read the usage field to track input and output tokens per call.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
import os

api_key = os.environ['LLM_API_KEY']  # never hard-code keys

system = 'You are a concise cooking assistant.'
history = [{'role': 'user', 'content': 'How long to boil an egg?'}]

# reply = client.chat(model=MODEL, system=system, messages=history)
# Exact call names differ by provider; check your SDK docs.
reply = 'About 7 minutes for a jammy yolk.'

history.append({'role': 'assistant', 'content': reply})
history.append({'role': 'user', 'content': 'And hard-boiled?'})
print(len(history), 'messages will be sent next turn')

The message history your app keeps and resends each turn.

A terminal chatbot that keeps recent history

You want a small command-line chat. Step 1: keep a history list. Step 2: on each turn, append the user's message, send the system prompt plus the last few messages, and append the reply. Step 3: keep an odd number of messages (7) so the slice always starts with a user message. The send function is a stub; replace its body with your SDK's chat call and return the reply text.

python
SYSTEM = "You are a concise cooking assistant."
KEEP = 7  # odd, so the slice starts with a user message
history: list[dict[str, str]] = []

def send(system: str, messages: list[dict[str, str]]) -> str:
    # Replace with your SDK call and return the reply text
    return f"(reply to: {messages[-1]['content']})"

while (text := input("you> ").strip()) not in ("", "quit"):
    history.append({"role": "user", "content": text})
    reply = send(SYSTEM, history[-KEEP:])
    history.append({"role": "assistant", "content": reply})
    print("bot>", reply)

You pushed an API key to GitHub

A key ended up in a public commit. Step 1: revoke it in the provider's console right away, because bots scan public repos for keys within minutes. Deleting the file is not enough; the key stays in Git history. Step 2: create a new key. Step 3: put it in a .env file that Git ignores, and load it in development. Step 4: in production, set it in your host's secret settings. Step 5: turn on a secret scanner (such as GitHub secret scanning or gitleaks) so it cannot happen again.

bash
# after revoking the old key and creating a new one:
echo ".env" >> .gitignore
echo "LLM_API_KEY=paste-new-key-here" > .env
pip install python-dotenv
python -c "from dotenv import load_dotenv; import os; load_dotenv(); print('LLM_API_KEY' in os.environ)"
git status   # .env must not appear in the list

Quick reference

  • Install the SDK in a virtual environment and pin its version
  • Read the API key from an environment variable; add .env to .gitignore first
  • The API is stateless: send the system prompt and history on every call
  • Check the stop reason: hitting the token limit means the reply was cut off
  • Log model, token usage and request ID for every call
  • Many APIs require messages to start with user and then alternate roles
  • A leaked key must be revoked; deleting it from the repo is not enough

Common mistakes

  • Committing API keys to Git.
  • Sending only the latest message and wondering why the model forgot context.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your bot forgets the user's name after one message. What is the most likely cause?

Question 2

2The response stop reason says the token limit was reached. What does that mean?

Question 3

3What should you never put in a system prompt?

Question 4

4A chat sends its full history each turn. How do total tokens grow as the conversation gets longer?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Install your provider's SDK, store the key in a .env file, and send one single-turn request. Print the reply, the stop reason and the token usage.

  2. Exercise 2medium

    Turn the terminal chatbot into one that keeps a running summary: when history passes 10 messages, replace the oldest 6 with a one-paragraph summary made by the model.

  3. Exercise 3hard

    Write a provider-neutral ChatClient Protocol with one method, complete(system, messages) -> Reply, and two implementations: a fake for tests and a real one using your SDK. Make the chatbot depend only on the Protocol.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use the official SDK or plain HTTP requests?
Use the official SDK for most work. It handles auth, retries, streaming and typed responses, and it is updated when the API changes.
Is there a free way to practise with chat APIs?
Some providers offer free trial credit or free tiers with low limits. You can also run a small open-weight model locally with Ollama, which exposes a local HTTP API.
What is the difference between the system prompt and the first user message?
The system prompt holds standing rules that apply to the whole conversation and carries more weight. User messages hold what the person asks, turn by turn.
Why does my request fail with a 401 error?
401 means the API key is missing, wrong or revoked. Check that the environment variable is set in the process that runs your code.
ShareXLinkedInWhatsApp