Title: A Step-by-Step Deep Dive into Enhancing an AI-Powered Python Productivity Script


Title: A Step-by-Step Deep Dive into Enhancing an AI-Powered Python Productivity Script

Introduction
In the quest to maximize daily productivity, it’s often the smallest tweaks and integrations that make the biggest differences. Previously, we showcased a straightforward Python script using the OpenAI API to generate an AI-assisted daily plan based on your tasks and schedule. This initial approach worked—pulling in to-dos, reading through a schedule, and using AI to produce a structured daily plan—but it was a starting point rather than a fully polished solution.

In this blog post, we’ll take a detailed look at an enhanced version of the script. We’ll break down the improvements made—such as sorting tasks by priority and deadline, adding Slack integration for easy sharing, and refining prompts—to help you understand why these changes matter and how you can adapt them to your own workflows.

Recap: What Did the Original Script Do?
The original code had three main components:

1. Fetching Tasks: It retrieved a list of tasks, each with attributes like task, deadline, priority, and notes.

2. Fetching Schedules: It similarly acquired a day’s schedule, listing events and their times.

3. AI-Generated Plan: Using the OpenAI API, it combined the above data into a prompt asking the model for a detailed, efficient daily plan and suggestions for prioritization.

While functional, this initial script was rudimentary. For instance, it didn’t sort tasks by urgency or priority, making the AI’s job a bit more complicated. It also lacked the ability to share the generated plan outside of the terminal, limiting its practical utility in a real-world office environment.

What’s New in the Enhanced Script?

1. Intelligent Task Sorting Based on Priority and Deadline
Originally, the tasks were just pulled in and handed off to the AI model without any preprocessing. By adding a sorting mechanism, we’re making the model’s job easier and our results more logical.

Why Sorting Helps:
Imagine you have three tasks: “Write Report (High Priority)”, “Send Client Email (Medium Priority)”, and “Check Documents (Low Priority)”. If you present them in random order, the AI will have to infer which to handle first. By sorting these tasks first by priority level (high > medium > low) and then by soonest deadline within each priority level, we give the model a clearer picture of what matters most. This can lead to more accurate and immediately actionable planning suggestions.

How It’s Done:
We define a PRIORITY_ORDER dictionary to numerically rank each priority:

PRIORITY_ORDER = {
"high": 1,
"medium": 2,
"low": 3
}

Using Python’s built-in sorted() function with a custom key lambda, we sort by (priority, deadline):

tasks_sorted = sorted(tasks, key=lambda t: (PRIORITY_ORDER[t['priority']], t['deadline']))

This ensures that tasks appear in a structured, meaningful order before the AI even sees them.

2. Slack Integration via Webhook
The previous iteration only printed out the daily plan to the console. While that’s fine for personal use, modern workflows often require sharing information across teams quickly and seamlessly. Slack is a common tool that teams rely on every day.

Why Integrate with Slack?
By posting the AI-generated plan directly to Slack, you can share the day’s agenda with your entire team in real-time. No need to copy-paste text from the terminal—just run the script, and the plan appears in your chosen Slack channel. This not only increases transparency but also allows everyone on your team to stay aligned on priorities.

How It’s Done:
We assume that you have a SLACK_WEBHOOK_URL stored in an environment variable. This is a common best practice, keeping sensitive details out of code.

SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")

We then define a post_to_slack() function:

def post_to_slack(message):
if SLACK_WEBHOOK_URL:
payload = {"text": message}
res = requests.post(SLACK_WEBHOOK_URL, json=payload)
if res.status_code == 200:
print("Slack message posted successfully.")
else:
print(f"Failed to send to Slack: {res.status_code}, {res.text}")
else:
print("No SLACK_WEBHOOK_URL set. Skipping Slack notification.")

After generating the daily plan, we simply call post_to_slack(daily_plan) to push the results to our Slack workspace.

3. Cleaner Code and Clearer Prompts
In addition to the new features, we’ve refined comments and the prompt sent to the AI model. Making code more readable is always a worthy investment, ensuring that others (and your future self) can understand the logic quickly.

Clearer Comments:
We’ve enhanced inline comments to explain what each section does, making it easier to maintain or modify the script later.

Refined Prompting Strategy:
The prompt given to the AI model has been slightly reorganized and clarified. The instructions to the AI are more explicit about the desired output format. While subtle, these improvements can lead to more consistently useful responses.

The Enhanced Script: A Close-Up

Below is the complete enhanced script for your reference:

import os
import requests
import openai
from datetime import datetime
from dotenv import load_dotenv

# Load environment variables (API keys, etc.)
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")

# Priority mapping for sorting tasks
PRIORITY_ORDER = {
"high": 1,
"medium": 2,
"low": 3
}

def get_todo_list():
"""Fetch the to-do list (dummy implementation).
In a real scenario, this might involve reading from a file or making an API call."""
tasks = [
{"task": "レポート作成", "deadline": "2024-12-15", "priority": "high", "notes": "財務分析"},
{"task": "顧客対応メール返信", "deadline": "2024-12-14", "priority": "medium", "notes": "A社担当者へのフォロー"},
{"task": "資料チェック", "deadline": "2024-12-14", "priority": "low", "notes": "細部確認"}
]
# Sort tasks by priority first, then by earliest deadline
tasks_sorted = sorted(tasks, key=lambda t: (PRIORITY_ORDER[t['priority']], t['deadline']))
return tasks_sorted

def get_schedule():
"""Fetch the schedule (dummy implementation).
In reality, this might use a Calendar API to get upcoming events."""
return [
{"event": "チームミーティング", "time": "2024-12-14T10:00:00"},
{"event": "ランチミーティング", "time": "2024-12-14T12:00:00"},
{"event": "顧客打合せ", "time": "2024-12-14T15:00:00"}
]

def generate_daily_plan(todo_list, schedule):
"""Generate a daily plan using OpenAI's API based on the given tasks and schedule."""
todo_text = "\n".join([
f"- {t['task']} (期限: {t['deadline']}, 優先度: {t['priority']}, メモ:{t['notes']})"
for t in todo_list
])
schedule_text = "\n".join([
f"- {e['event']} ({e['time']})" for e in schedule
])

prompt = f"""
あなたは有能なアシスタントAIです。
以下は本日のタスク一覧と予定です。
これらを考慮して、最も効率的な1日の行動計画とタスク完了のための戦略を提案してください。

【タスク一覧】
{todo_text}

【スケジュール一覧】
{schedule_text}

出力フォーマット:
1. 本日の最重要タスク
2. 本日の行動計画(時系列)
3. タスク遂行時のポイントや留意事項
"""

response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "あなたは有能なタスクプランナーです。"},
{"role": "user", "content": prompt}
],
temperature=0.5
)

return response.choices[0].message.content.strip()

def post_to_slack(message):
"""Post the generated plan to Slack using a webhook URL."""
if SLACK_WEBHOOK_URL:
payload = {"text": message}
res = requests.post(SLACK_WEBHOOK_URL, json=payload)
if res.status_code == 200:
print("Slack message posted successfully.")
else:
print(f"Failed to send to Slack: {res.status_code}, {res.text}")
else:
print("No SLACK_WEBHOOK_URL set. Skipping Slack notification.")

if __name__ == "__main__":
# Fetch tasks and schedule
todos = get_todo_list()
schedule = get_schedule()

# Generate the AI-assisted daily plan
daily_plan = generate_daily_plan(todos, schedule)

# Print the daily plan to the console
print("=== 本日のAIプラン ===")
print(daily_plan)

# Optionally post the plan to Slack
post_to_slack(daily_plan)

Adapting the Code for Your Own Use
Now that you’ve seen the enhanced code and understand its logic, consider how you might adapt it for your specific environment:

Different Data Sources:
Instead of using a hard-coded list of tasks, integrate a project management tool’s API (like Todoist, Trello, or Asana) to pull real tasks.

Authentication & Security:
Keep your API keys secure in environment variables or a secret manager. Avoid hardcoding credentials in code.

Additional Integrations:
Beyond Slack, you might want to:

Email the plan to your team.

Store it in a database for historical review.

Visualize it in a dashboard using frameworks like Streamlit.

Fine-Tuning the AI Model:
Experiment with the prompt or temperature parameter to control the creativity and style of the AI’s response. You might prefer a more conservative (temperature=0.0) approach for consistent results, or a slightly higher value for more brainstorming-like suggestions.

Conclusion
This enhanced script demonstrates that even small adjustments—like sorting tasks or adding Slack notifications—can significantly improve the usability and impact of a simple AI-powered tool. By structuring your input data more intelligently and integrating with your team’s communication platforms, you’re moving towards a more automated, efficient, and collaborative workflow.

As AI services become more integrated into everyday productivity, taking the time to refine prompts, organize data, and seamlessly share insights will become increasingly essential. With these enhancements, you’re on your way to leveraging AI not just for novel experimentation, but as a reliable partner in managing your day-to-day activities.


コメント

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です