AsyncAgentScheduler Quick Start (run_immediately=True) runs the agent twice at start

Aperta Adatta ai principianti
#6,710 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
82/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Leggi praisonai/scheduler/async_agent_scheduler.py intorno a _run_schedule (390–423) e start() (252–256), poi controlla ScheduleTicker.is_due in shared.py (85–92). Segui la prima iterazione dell’intervallo dopo run_immediately=True e usa lo script di riproduzione nell’issue per verificare la correzione. Il lavoro è completato quando l’avvio produce un’esecuzione e quelle successive rispettano l’intervallo richiesto.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Description

The AsyncAgentScheduler Quick Start starts the scheduler with

await scheduler.start("hourly", max_retries=3, run_immediately=True)

and expects one run now and the next in an hour. The agent runs twice at
start: once inside start() (run_immediately), and again as soon as the
background loop's first iteration begins.

For an interval schedule such as "hourly", _run_schedule
(praisonai/scheduler/async_agent_scheduler.py, 390–423) sleeps only for cron
schedules before running (if ticker.is_cron and not ticker.is_due()), so its
first iteration runs at once, right after the immediate run in start()
(252–256). ScheduleTicker.is_due (shared.py 85–92) returns True for
interval schedules.

For a job with side effects (a payment, an email, a post), every scheduler
start, including every process restart, runs it twice.

Environment

Python SDK, praisonai 4.8.0 with praisonaiagents 1.8.0. Provider: OpenAI-compatible, played by a local fake endpoint (no API key). Python 3.13 on Windows 11.

Reproduction

Re-checked on 2026-11-19 against praisonai 4.8.0 and praisonaiagents 1.8.0, the current releases: same result, two executions at start. The output below and the line numbers above are from 4.8.0.

Self-contained script below (pip install praisonai==4.8.0, then python repro.py). No API key; nothing leaves 127.0.0.1. It is the Quick Start's
agent and start(...) call, pointed at a local fake OpenAI endpoint that
counts requests.

Output:

praisonai 4.8.0, praisonaiagents 1.8.0
model requests in the first 20 s: 2, at [2.3, 2.3] s after start()
stats: {'is_running': False, 'total_executions': 2, 'successful_executions': 2, 'failed_executions': 0, 'success_rate': 100.0, 'total_cost_usd': 0.0, 'remaining_budget': 1.0, 'runtime_seconds': 22.332849, 'cost_per_execution': 0.0, 'delivered_deliveries': 0, 'undelivered_deliveries': 0}
Expected

One execution at start with run_immediately=True, then one per interval.

Suggestion

After an immediate run, have the interval loop sleep one interval before its
first iteration (for example, skip the first iteration when
ticker.last_run_at was just set by start()).

repro.py
# --- repro.py (verbatim) ---
"""PraisonAI AsyncAgentScheduler: the Quick Start's `start("hourly", max_retries=3,
run_immediately=True)` runs the agent twice at start, not once.

`pip install praisonai==4.7.11` then `python repro.py`. No API key; nothing leaves
127.0.0.1. The agent is the Quick Start's, pointed at a local fake OpenAI endpoint
that answers every request and counts them. Nothing in PraisonAI is patched.
"""

import asyncio
import json
import os
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

REQUESTS: list = []


class FakeOpenAI(BaseHTTPRequestHandler):
    def do_POST(self):  # noqa: N802
        json.loads(self.rfile.read(int(self.headers["Content-Length"])))
        REQUESTS.append(time.time())
        data = json.dumps({"id": "x", "object": "chat.completion", "created": 0, "model": "gpt-4o-mini",
                           "choices": [{"index": 0, "finish_reason": "stop",
                                        "message": {"role": "assistant", "content": "- one\n- two\n- three"}}],
                           "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}}).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


server = ThreadingHTTPServer(("127.0.0.1", 8982), FakeOpenAI)
server.daemon_threads = True
threading.Thread(target=server.serve_forever, daemon=True).start()
os.environ.update(OPENAI_API_KEY="placeholder-not-a-key", OPENAI_BASE_URL="http://127.0.0.1:8982/v1")

from importlib.metadata import version  # noqa: E402

from praisonai.scheduler import AsyncAgentScheduler  # noqa: E402
from praisonaiagents import Agent  # noqa: E402


async def main():
    agent = Agent(name="NewsChecker", instructions="Summarise today's AI news in 3 bullet points.",
                  llm="gpt-4o-mini")
    scheduler = AsyncAgentScheduler(agent, task="Check the latest AI news")
    t0 = time.time()
    await scheduler.start("hourly", max_retries=3, run_immediately=True)
    await asyncio.sleep(20)  # well inside the first hour
    await scheduler.stop()
    print(f"model requests in the first 20 s: {len(REQUESTS)}, at "
          f"{[round(t - t0, 1) for t in REQUESTS]} s after start()", flush=True)
    print(f"stats: {await scheduler.get_stats()}", flush=True)


print(f"praisonai {version('praisonai')}, praisonaiagents {version('praisonaiagents')}", flush=True)
asyncio.run(main())
# --- end repro.py ---
Lingua principale
Python
Stelle
9.3k
Fork
1.5k
Merge medio
1g 5h
PR unite (30g)
520

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di MervinPraison/PraisonAI

Tutte le issue di MervinPraison/PraisonAI

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.