How to make AI return a table
gpt-4o.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the openai Python package and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
Use the gpt-4o model with a prompt that explicitly requests a table in markdown format. The example below shows a complete runnable Python script that sends a prompt and prints the AI's table response.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = (
"Generate a markdown table showing the top 3 programming languages in 2026 with columns: Language, Popularity (%), and Release Year."
)
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
print(response.choices[0].message.content) | Language | Popularity (%) | Release Year | |------------|----------------|--------------| | Python | 29 | 1991 | | JavaScript | 19 | 1995 | | Rust | 8 | 2010 |
Common variations
You can request tables in CSV or JSON formats by adjusting the prompt. For asynchronous calls or streaming, use the respective SDK methods. Switching to claude-3-5-sonnet-20241022 can improve code and table formatting quality.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = "You are a helpful assistant that returns data tables in CSV format."
user_prompt = (
"List the top 3 programming languages in 2026 with columns: Language, Popularity (%), Release Year in CSV."
)
message = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=200,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}]
)
print(message.content[0].text) Language,Popularity (%),Release Year Python,29,1991 JavaScript,19,1995 Rust,8,2010
Troubleshooting
If the AI returns unstructured text instead of a table, clarify the format explicitly in your prompt (e.g., "Return the data as a markdown table" or "Provide CSV output"). If the table is incomplete, increase max_tokens. For parsing issues, request output in JSON format for easier programmatic handling.
Key Takeaways
- Always specify the exact table format (markdown, CSV, JSON) in your prompt for consistent output.
- Provide column headers and example rows in the prompt to guide the AI's table structure.
- Use
max_tokenssettings high enough to avoid truncated tables. - Switch models like
claude-3-5-sonnet-20241022for improved table formatting quality. - Explicitly request parsable formats to simplify downstream processing.