How to beginner · 3 min read

How to save CrewAI output to file

Quick answer
Use Python's file handling to save CrewAI output by capturing the response string and writing it to a file with open(). After calling CrewAI's API, write the output text to a file using file.write().

PREREQUISITES

  • Python 3.8+
  • CrewAI API key
  • pip install crewai-sdk (or relevant SDK)
  • Basic knowledge of Python file I/O

Setup

Install the CrewAI SDK and set your API key as an environment variable for secure access.

bash
pip install crewai-sdk

# In your shell or environment setup
export CREWAI_API_KEY=os.environ["CREWAI_API_KEY"]

Step by step

This example shows how to call CrewAI's text generation and save the output to a local file named output.txt.

python
import os
from crewai import CrewAIClient

# Initialize client with API key from environment
client = CrewAIClient(api_key=os.environ["CREWAI_API_KEY"])

# Generate text from CrewAI
response = client.generate_text(prompt="Write a short poem about spring.")

# Extract the generated text
output_text = response.text

# Save output to file
with open("output.txt", "w", encoding="utf-8") as file:
    file.write(output_text)

print("CrewAI output saved to output.txt")
output
CrewAI output saved to output.txt

Common variations

  • Use open("output.txt", "a") to append instead of overwrite.
  • Save JSON output by serializing response if it contains metadata.
  • Use async SDK methods if supported for non-blocking calls.

Troubleshooting

  • If you get a FileNotFoundError, ensure the directory exists or use an absolute path.
  • If the API key is invalid, verify CREWAI_API_KEY is set correctly in your environment.
  • Check for network issues if the API call fails.

Key Takeaways

  • Always retrieve your CrewAI API key securely from environment variables.
  • Use Python's built-in open() and write() to save AI output to files.
  • Appending to files allows you to keep logs of multiple AI outputs.
  • Check file paths and permissions to avoid common file I/O errors.
  • Consider serializing full API responses if you need metadata along with text.
Verified 2026-04 · crewai-text-generation
Verify ↗