Receiving AI Output
After sending a request to the AI API, you receive a JSON response. You need to extract the text content from this response to use it in your application.
8 min•By Priygop Team•Updated 2026
Extracting Output from the API Response
Extracting Output from the API Response
# How to extract the AI's text response from the API response JSON
def extract_ai_response(api_response):
"""
Extract the text content from an OpenAI API response.
The response is a complex JSON object. The actual text
is nested inside choices[0].message.content
"""
try:
# Navigate the nested response structure
choices = api_response.get("choices", [])
if not choices:
return None # No choices in response
# Get the first (and usually only) choice
first_choice = choices[0]
# Get the message from the choice
message = first_choice.get("message", {})
# Get the text content from the message
content = message.get("content", "")
return content.strip() # Remove leading/trailing whitespace
except (KeyError, IndexError, AttributeError) as e:
print(f"Error extracting response: {e}")
return None
# Example with a sample API response
sample_response = {
"choices": [
{
"message": {
"role": "assistant",
"content": " Machine learning is a way of teaching computers by example. "
},
"finish_reason": "stop"
}
],
"usage": {"total_tokens": 87}
}
text = extract_ai_response(sample_response)
print(f"Extracted text: '{text}'")
print(f"Text length: {len(text)} characters")Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence