โ† Resources
tutorialยท
Apr 20, 2026ยท8 min

Agent Task Scheduling LangChain: Morning Briefing Bot

By Govind Kavaturi

LangChain agent with CueAPI scheduling dashboard showing delivery confirmation and outcome tracking

Your LangChain agent runs every morning at 7am to summarize the news. Three weeks in, you discover it's been failing silently for a week. Users noticed. You didn't. This is the accountability gap every AI builder faces.

Agent task scheduling langchain requires more than just firing your agent on a timer. You need delivery confirmation, outcome tracking, and evidence the work actually happened. Platform schedulers leave you blind to silent failures. CueAPI makes your LangChain agents accountable.

TL;DR: Build a news summarization agent with LangChain that runs on schedule, reports its success, and provides evidence it worked. Use CueAPI for delivery confirmation and outcome tracking instead of hoping your platform scheduler didn't fail silently.

Key Takeaways: - CueAPI retries failed deliveries 3 times with exponential backoff (1, 5, 15 minutes) - Outcome reporting gives you time to confirm your agent did the work - Evidence storage lets you track external proof like tweet IDs or email batch numbers - Silent failures cost you users who notice broken agents before you do - 99.97% delivery confirmation vs platform schedulers that fire and forget

Why Morning Briefing Agents Need Accountability

Platform schedulers treat your LangChain agent like a script. They fire the request and forget about it. Your agent could crash on startup, fail to connect to the LLM, or return an empty response. The scheduler reports "success" because it sent the HTTP request.

This creates the accountability gap. Your agent runs but doesn't work. Cron has no concept of success because it was built for scripts, not agents. LangChain agents need to report back with proof they completed their mission.

โš ๏ธ Warning: Platform schedulers only track delivery, not outcomes. Your agent could fail every day for a month and you'd never know until a user complains.

What You'll Build: A News Summarization Agent with CueAPI

Your agent will:

  • Fetch top headlines from NewsAPI every morning at 7am
  • Use OpenAI to generate a 3-bullet summary
  • Post the summary to a webhook endpoint
  • Report outcome and evidence back to CueAPI
  • Retry automatically if any step fails

By the end, you'll have an agent that runs reliably and proves it worked.

Step 1: Set Up Your LangChain Agent Environment

Install the required packages for your news summarization agent:

pip install langchain openai requests httpx python-dotenv

Create your environment file with API keys:

OPENAI_API_KEY=sk-...
NEWSAPI_KEY=your_newsapi_key
CUEAPI_SECRET_KEY=cue_sk_...
WEBHOOK_URL=https://your.endpoint.com/briefing

๐Ÿ“ Note: Get your NewsAPI key free at newsapi.org. CueAPI keys are free at dashboard.cueapi.ai.

Expected output: All packages installed, environment configured.

Step 2: Create Your News Summarization Agent

Build your LangChain agent that fetches news and creates summaries:

# morning_agent.py
import os
import requests
from datetime import datetime
from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from dotenv import load_dotenv

load_dotenv()

class MorningBriefingAgent:
    def __init__(self):
        self.llm = OpenAI(temperature=0.3)
        self.news_api_key = os.getenv('NEWSAPI_KEY')
        self.webhook_url = os.getenv('WEBHOOK_URL')
        
    def fetch_headlines(self):
        url = f"https://newsapi.org/v2/top-headlines?country=us&pageSize=10&apiKey={self.news_api_key}"
        response = requests.get(url)
        response.raise_for_status()
        
        articles = response.json()['articles']
        headlines = [article['title'] for article in articles[:5]]
        return headlines
    
    def generate_summary(self, headlines):
        prompt = PromptTemplate(
            input_variables=["headlines"],
            template="""
            Create a 3-bullet executive summary of these news headlines:
            
            {headlines}
            
            Format as:
            โ€ข [Brief insight about headline 1-2]
            โ€ข [Brief insight about headline 3-4] 
            โ€ข [Brief insight about headline 5]
            
            Each bullet should be one sentence, maximum 25 words.
            """
        )
        
        chain = LLMChain(llm=self.llm, prompt=prompt)
        headlines_text = "\n".join(f"{i+1}. {headline}" for i, headline in enumerate(headlines))
        
        summary = chain.run(headlines=headlines_text)
        return summary.strip()
    
    def post_briefing(self, summary):
        payload = {
            "summary": summary,
            "timestamp": datetime.now().isoformat(),
            "source": "morning-briefing-agent"
        }
        
        response = requests.post(self.webhook_url, json=payload)
        response.raise_for_status()
        return response.json()
    
    def run(self):
        try:
            headlines = self.fetch_headlines()
            summary = self.generate_summary(headlines)
            result = self.post_briefing(summary)
            
            return {
                "success": True,
                "headlines_count": len(headlines),
                "summary_length": len(summary),
                "posted_at": result.get('id', 'unknown')
            }
        except Exception as e:
            return {
                "success": False,
                "error": str(e)
            }

if __name__ == "__main__":
    agent = MorningBriefingAgent()
    result = agent.run()
    print(f"Agent result: {result}")

Test your agent locally:

python morning_agent.py

Expected output: Your agent fetches news, generates a summary, and posts it to your webhook.

Step 3: Schedule Your Agent with CueAPI

Create a CueAPI cue that schedules your agent to run every morning:

# setup_cue.py
import requests
import os
from dotenv import load_dotenv

load_dotenv()

headers = {
    "Authorization": f"Bearer {os.getenv('CUEAPI_SECRET_KEY')}",
    "Content-Type": "application/json"
}

cue_data = {
    "name": "morning-briefing-agent",
    "description": "Daily news summary at 7am Eastern",
    "schedule": {
        "type": "recurring",
        "cron": "0 7 * * *",
        "timezone": "America/New_York"
    },
    "transport": "webhook",
    "callback": {
        "url": "https://your.agent.endpoint.com/run",
        "method": "POST",
        "headers": {"X-Agent-Secret": "your_secret_here"}
    },
    "retry": {
        "max_attempts": 3,
        "backoff_minutes": [1, 5, 15]
    },
    "on_failure": {
        "email": True,
        "pause": False
    }
}

response = requests.post("https://api.cueapi.ai/v1/cues", headers=headers, json=cue_data)
cue = response.json()

print(f"Created cue: {cue['id']}")
print(f"Next run: {cue['next_run']}")

Or use curl:

curl -X POST https://api.cueapi.ai/v1/cues \
  -H "Authorization: Bearer cue_sk_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "morning-briefing-agent",
    "schedule": {
      "type": "recurring",
      "cron": "0 7 * * *",
      "timezone": "America/New_York"
    },
    "transport": "webhook",
    "callback": {
      "url": "https://your.agent.endpoint.com/run",
      "method": "POST"
    },
    "retry": {
      "max_attempts": 3,
      "backoff_minutes": [1, 5, 15]
    }
  }'

๐Ÿ“ Note: Replace your.agent.endpoint.com with your actual agent URL. This could be a Replit app, OpenClaw function, or any HTTP endpoint.

Expected output: CueAPI returns your cue ID and confirms the next scheduled run at 7am Eastern.

Step 4: Add Outcome Reporting to Your Agent

Modify your agent to report success back to CueAPI with evidence:

# enhanced_morning_agent.py
import os
import requests
from datetime import datetime
from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from dotenv import load_dotenv

load_dotenv()

class AccountableMorningAgent:
    def __init__(self):
        self.llm = OpenAI(temperature=0.3)
        self.news_api_key = os.getenv('NEWSAPI_KEY')
        self.webhook_url = os.getenv('WEBHOOK_URL')
        self.cueapi_key = os.getenv('CUEAPI_SECRET_KEY')
        
    def run_with_accountability(self, execution_id):
        headers = {"Authorization": f"Bearer {self.cueapi_key}"}
        
        try:
            # Your existing agent logic
            headlines = self.fetch_headlines()
            summary = self.generate_summary(headlines)
            post_result = self.post_briefing(summary)
            
            # Report success to CueAPI
            outcome_data = {
                "success": True,
                "result": f"Generated summary from {len(headlines)} headlines",
                "metadata": {
                    "headlines_processed": len(headlines),
                    "summary_length": len(summary),
                    "posted_at": datetime.now().isoformat()
                }
            }
            
            outcome_response = requests.post(
                f"https://api.cueapi.ai/v1/executions/{execution_id}/outcome",
                headers=headers,
                json=outcome_data
            )
            
            return {"success": True, "outcome": outcome_response.json()}
            
        except Exception as e:
            # Report failure to CueAPI
            failure_data = {
                "success": False,
                "result": "Failed to generate morning briefing",
                "metadata": {"error_type": type(e).__name__, "error": str(e)}
            }
            
            requests.post(
                f"https://api.cueapi.ai/v1/executions/{execution_id}/outcome",
                headers=headers,
                json=failure_data
            )
            
            return {"success": False, "error": str(e)}

    # Include your existing fetch_headlines, generate_summary, post_briefing methods here

def handle_cueapi_request(request):
    """Handle incoming CueAPI webhook"""
    execution_id = request.headers.get('X-CueAPI-Execution-ID')
    agent = AccountableMorningAgent()
    return agent.run_with_accountability(execution_id)

โš ๏ธ Warning: Always report an outcome within a reasonable timeframe or CueAPI will mark the execution as timed out.

Expected output: Your agent now reports success/failure back to CueAPI with detailed metadata and evidence.

Step 5: Test Your Scheduled Agent

Trigger your cue manually to test the full flow:

# test_trigger.py
import requests
import os

headers = {"Authorization": f"Bearer {os.getenv('CUEAPI_SECRET_KEY')}"}

# Replace with your actual cue ID
cue_id = "cue_..."
response = requests.post(f"https://api.cueapi.ai/v1/cues/{cue_id}/trigger", headers=headers)
execution = response.json()

print(f"Triggered execution: {execution['id']}")
print(f"Status: {execution['status']}")
print(f"Scheduled for: {execution['scheduled_for']}")

Or use curl:

curl -X POST https://api.cueapi.ai/v1/cues/cue_.../trigger \
  -H "Authorization: Bearer cue_sk_..."

Check the execution status:

execution_response = requests.get(f"https://api.cueapi.ai/v1/executions/{execution['id']}", headers=headers)
execution_status = execution_response.json()
print(f"Delivery status: {execution_status['delivery_status']}")
print(f"Outcome: {execution_status.get('outcome')}")

Expected output: CueAPI confirms delivery to your agent and shows the reported outcome with your evidence.

โœ… Success: If you see delivery_status: "delivered" and outcome.success: true, your agent is fully accountable.

Step 6: Monitor and Debug Your Agent in Production

View your agent's execution history in the CueAPI dashboard:

# monitor_agent.py
import requests
import os

headers = {"Authorization": f"Bearer {os.getenv('CUEAPI_SECRET_KEY')}"}

# Get recent executions for your cue
cue_id = "cue_..."
response = requests.get(f"https://api.cueapi.ai/v1/cues/{cue_id}/executions?limit=10", headers=headers)
executions = response.json()

for exec in executions['data']:
    print(f"Execution {exec['id']}:")
    print(f"  Scheduled: {exec['scheduled_for']}")
    print(f"  Delivered: {exec['delivery_status']}")
    print(f"  Outcome: {exec.get('outcome', {}).get('success')}")
    print()

Set up failure alerts to catch problems immediately:

# Update your cue with email alerts
update_data = {
    "on_failure": {
        "email": True,
        "webhook": "https://your.monitoring.com/alert",
        "pause": False
    }
}

requests.patch(f"https://api.cueapi.ai/v1/cues/{cue_id}", headers=headers, json=update_data)

๐Ÿ“ Note: CueAPI sends failure alerts within minutes, not hours. No more discovering broken agents from user complaints.

Expected output: Full visibility into your agent's execution history, delivery confirmation, and outcome tracking.

Beyond Basic Scheduling: Adding Evidence and Retries

CueAPI gives you execution visibility that platform schedulers can't match. Your morning briefing agent now provides:

  • Delivery confirmation: CueAPI confirms your agent received the job with a signed payload
  • Outcome tracking: Your agent reports back with proof it completed the work
  • Evidence storage: External IDs and URLs prove the business action happened
  • Automatic retries: Failed deliveries retry 3 times with exponential backoff
  • Failure alerts: Email notifications within minutes of agent failures

This is what scheduling for AI agents looks like. Not just firing requests into the void. Accountability built in.

๐Ÿ“ Note: For OpenClaw users, check out our CueAPI OpenClaw setup guide for platform-specific configuration.

Your agent runs anywhere - Replit, OpenClaw, Mac Mini, private server. CueAPI makes it accountable everywhere. This is how you build trustworthy infrastructure for AI agents.

Frequently Asked Questions

Can I use CueAPI with other LangChain agent types?

Yes. CueAPI works with any HTTP endpoint. LangSmith agents, AutoGPT, custom chains - if it accepts HTTP requests, CueAPI can schedule it with accountability.

What happens if my agent takes longer than expected to complete?

Your agent should report outcomes in a timely manner. CueAPI provides reasonable timeouts for outcome reporting.

How do I handle agents that need to run multiple times per day?

Use multiple cron expressions or create separate cues. For example: "0 7,12,18 *" runs at 7am, 12pm, and 6pm daily.

Can I pause my agent if it fails multiple times?

Set "pause": true in your on_failure configuration. CueAPI will automatically pause your cue after the configured number of consecutive failures.

Does CueAPI work with LangSmith tracing?

Yes. Your LangChain agent can report to both LangSmith for tracing and CueAPI for scheduling accountability. They serve different purposes and work together.

Make your agents accountable. Know they worked. Get on with building.


Try it yourself. Free tier available. Get your API key at dashboard.cueapi.ai.

Sources

  • LangChain: Python framework for building applications with large language models: https://python.langchain.com/docs/
  • NewsAPI: REST API for live worldwide news data: https://newsapi.org/
  • OpenAI API: Language model API for text generation: https://platform.openai.com/docs/api-reference
  • CueAPI Python SDK: Scheduling API with delivery confirmation: https://docs.cueapi.ai/sdk/python

About the author: Govind Kavaturi is co-founder of Vector, a portfolio of AI-native products. He believes the next phase of the internet is built for agents, not humans.

Get started

pip install cueapi
Get API Key โ†’

Related Articles

Continue Learning

Start hereSchedule Your First Agent Task in 5 Minutes
How do I know if my agent ran successfully?
Ctrl+K