datawhalechina/hello-agents · error · AgentException

任务不存在: {task_id}

Error message

任务不存在: {task_id}

What it means

Lookup guard in ControllerAgent.execute_task: the given task_id is not a key in self.active_tasks. Tasks enter that dict only via submit_task and are removed in the finally block of execute_task, so the ID is unknown (never submitted, typo'd) or already finished — after completion the task moves to task_history and a second execute call with the same ID fails here.

Source

Thrown at Co-creation-projects/Apricity-InnocoreAI/agents/controller.py:107

            "callback": callback,
            "created_at": datetime.now(),
            "started_at": None,
            "completed_at": None,
            "result": None,
            "error": None,
            "agent_results": {}
        }
        
        self.active_tasks[task_id] = task
        await self.task_queue.put((priority, task))
        
        logger.info(f"任务已提交: {task_id}, 类型: {task_type.value}")
        return task_id
    
    async def execute_task(self, task_id: str) -> Dict[str, Any]:
        """执行单个任务"""
        if task_id not in self.active_tasks:
            raise AgentException(f"任务不存在: {task_id}")
        
        task = self.active_tasks[task_id]
        
        async with self.semaphore:  # 并发控制
            try:
                task["status"] = TaskStatus.RUNNING
                task["started_at"] = datetime.now()
                
                await self._trigger_event("task_started", task)
                
                # 根据任务类型执行相应的逻辑
                if task["type"] == TaskType.PAPER_HUNTING:
                    result = await self._execute_paper_hunting(task)
                elif task["type"] == TaskType.PAPER_ANALYSIS:
                    result = await self._execute_paper_analysis(task)
                elif task["type"] == TaskType.WRITING_ASSISTANCE:
                    result = await self._execute_writing_assistance(task)
                elif task["type"] == TaskType.CITATION_VALIDATION:

View on GitHub (pinned to 606a07d341)

Solutions

  1. Use the exact ID returned by submit_task, kept as a string, and execute it once.
  2. For re-execution, submit a new task instead of reusing a completed ID.
  3. Before raising, fall back: if task_id in self.task_history, report 'task already finished' instead of 'not found' for clearer UX.
  4. Persist task registry (or query task_history) if the controller outlives requests.

Example fix

# before
if task_id not in self.active_tasks:
    raise AgentException(f"任务不存在: {task_id}")

# after
if task_id not in self.active_tasks:
    done = next((t for t in self.task_history if t["id"] == task_id), None)
    if done:
        raise AgentException(f"任务 {task_id} 已结束(状态: {done['status']}),不能重复执行")
    raise AgentException(f"任务不存在: {task_id}"); 
Defensive patterns

Strategy: validation

Validate before calling

# Caller-side: only execute ids you got from submit_task, exactly once
if not isinstance(task_id, str) or not task_id:
    raise ValueError("task_id must be a non-empty string")
if task_id not in controller.active_tasks:
    done = any(t["id"] == task_id for t in controller.task_history)
    status = "already finished" if done else "unknown id"
    raise ValueError(f"cannot execute {task_id!r}: {status}")

Type guard

def is_active_task(controller, task_id: str) -> bool:
    return isinstance(task_id, str) and task_id in controller.active_tasks

Try / catch

try:
    result = await controller.execute_task(task_id)
except AgentException as e:
    if "任务不存在" in str(e):
        task_id = await controller.submit_task(...)  # resubmit and execute the new id
        result = await controller.execute_task(task_id)
    else:
        raise

Prevention

When it happens

Trigger: Calling execute_task('abc') with an ID not returned by submit_task; retrying execute_task after a successful first run (ID moved to task_history in finally); racing a background worker that executed the queued task first; string-vs-int ID mismatch from JSON deserialization.

Common situations: API handler extracting task_id from URL with wrong type/whitespace; double-click on an 'execute' endpoint; frontend caching an old task ID after backend restart wiped in-memory state (active_tasks is not persisted).

Related errors


AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14). Data as JSON: /api/errors/d9b706fa8cd798d0. Report an issue: GitHub.