👨💻 はじめに
Googleでシニアソフトウェアエンジニアを務める山田です。今回の「実践テクニック&チュートリアル」シリーズでは、ChatGPT APIを活用したタスク自動化システムの構築方法を、実際のコード例を交えて詳しく解説します。
特に、メール自動返信やデータ分析レポート生成など、日常業務で役立つ具体的なユースケースを想定し、Pythonを使った実装方法をステップバイステップで紹介します。
📌 この記事で学べること:
- ChatGPT APIの効率的な呼び出し方法
- Pythonを使ったタスク自動化スクリプトの作成
- エラー処理とログ管理のベストプラクティス
🚀 1. ChatGPT APIの基本設定
✓ APIキーの取得と設定:
import openai
# APIキーの設定
openai.api_key = "your-api-key"
def call_chatgpt(prompt):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=1000
)
return response.choices[0].message.content
✓ プロンプト設計のコツ:
- 具体的な指示を出す
- 出力形式を指定する(例: JSON, Markdown)
💡 2. 実践的な自動化スクリプト例
✓ メール自動返信システム:
import smtplib
from email.mime.text import MIMEText
def auto_reply_email(subject, body):
prompt = f"""
以下のメールに対して、丁寧な返信を日本語で作成してください。
件名: {subject}
本文: {body}
"""
reply = call_chatgpt(prompt)
msg = MIMEText(reply)
msg['Subject'] = f"Re: {subject}"
msg['From'] = "your-email@example.com"
msg['To'] = "client@example.com"
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login("your-email@example.com", "your-password")
server.send_message(msg)
✓ データ分析レポート生成:
import pandas as pd
def generate_report(csv_path):
data = pd.read_csv(csv_path)
summary = data.describe().to_markdown()
prompt = f"""
以下のデータの概要をもとに、ビジネス向けの分析レポートをMarkdown形式で作成してください。
データ概要:
{summary}
"""
report = call_chatgpt(prompt)
with open("report.md", "w") as f:
f.write(report)
🔧 3. エラー処理とログ管理
✓ リトライメカニズムの実装:
import time
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def safe_call_chatgpt(prompt):
try:
return call_chatgpt(prompt)
except Exception as e:
print(f"Error: {e}")
raise
✓ ログ管理の設定:
import logging
logging.basicConfig(
filename='chatgpt_automation.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logging.info("Automation script started")
🎯 4. さらに活用するためのヒント
✓ テンプレートの活用:
TEMPLATES = {
"meeting_minutes": """
以下の会話の議事録を作成してください:
{content}
フォーマット:
- 日時:
- 参加者:
- 決定事項:
- アクションアイテム:
"""
}
minutes = call_chatgpt(TEMPLATES["meeting_minutes"].format(content=meeting_text))
✓ コスト管理の方法:
- トークン使用量のモニタリング
- キャッシュの活用
📌 まとめ:今日から始める3つのステップ
- APIキーを取得して基本設定を行う
- 具体的なユースケースに沿ってスクリプトを作成
- エラー処理とログ管理を実装して信頼性を向上
💬 皆さんが自動化したいタスクがあれば、コメントで教えてください!
次回は「Docker Composeで最速開発環境を構築する方法」を解説予定です。
「参考になった!」と思ったら♡やリポストをお願いします! 🚀