Using an AI model in your own program means calling its API, conceptually identical to calling any other web API - just with a prompt as the input.
A basic API call (Python example)
import requests
API_KEY = "your-api-key-here"
response = requests.post(
"https://api.example-ai-provider.com/v1/chat",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"model": "example-model",
"messages": [
{"role": "user", "content": "Explain recursion in one paragraph."}
]
}
)
result = response.json()
print(result["choices"][0]["message"]["content"])
Every major AI provider's API follows this same basic shape: send a prompt (often as a list of messages), get back generated text in the response.
Keep your API key out of your code
Never hardcode an API key directly in a file you might commit to GitHub or upload publicly. Load it from an environment variable instead:
import os
API_KEY = os.environ.get("AI_API_KEY")
This is exactly the same principle this site's own PHP config file follows for its own secrets - credentials live outside the code that gets shared or committed.
System prompts: setting behavior for the whole conversation
messages = [
{"role": "system", "content": "You are a concise coding tutor. Keep answers under 100 words."},
{"role": "user", "content": "What is a variable?"}
]
The system message sets persistent instructions the model should follow throughout the conversation, separate from the user's actual question.
Handling failures
API calls can fail - rate limits, network issues, invalid input. Always check the response status and handle failure gracefully rather than assuming success:
if response.status_code != 200:
print("AI request failed:", response.status_code)
else:
result = response.json()