Module 6: Calling an AI service from Python · 11 min
Sending a prompt to a model
Every AI company has its own address and exact message format, so always copy the current shape from the provider's documentation. The pattern is the same everywhere: send your prompt and key as JSON, read the JSON reply, and handle errors.
import os
import requests
def ask(prompt):
url = "https://api.example.com/v1/chat" # use your provider's real address
headers = {"Authorization": "Bearer " + os.environ["MY_AI_KEY"]}
body = {"model": "model-name", "messages": [{"role": "user", "content": prompt}]}
r = requests.post(url, headers=headers, json=body, timeout=60)
r.raise_for_status() # stop with a clear error if status is not OK
return r.json() # then pick the answer text out of this data
# print(ask("Explain a Python list in one sentence."))
Many providers also offer an official Python package that does these steps for you. Combine this lesson with the Prompt Engineering and Agentic AI courses to build real tools.
You have now finished the lessons. Take the final exam to earn your certificate.