File size: 3,742 Bytes
3c5146b
 
 
 
3a148fe
3c5146b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a148fe
 
 
 
 
 
 
 
 
 
3c5146b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7265217
3c5146b
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Date Agent — estimates missing project dates using Haiku. Three modes: A (both provided), B (start only), C (end only)."""

import json, os
import anthropic
from json_repair import repair_json
from pydantic import BaseModel
from typing import Optional
from core.date_engine import detect_date_mode
from core.planner import ERROR_MESSAGES


class DateResult(BaseModel):
    estimated_start_date: Optional[str] = None
    estimated_end_date: Optional[str] = None
    timeline_note: Optional[str] = None


# PROMPT v1.0
SYSTEM_PROMPT = """
You are a project scheduling expert.
Given a project scope, estimate missing dates.
Return ONLY valid JSON:
{
  "estimated_start_date": "YYYY-MM-DD or null",
  "estimated_end_date": "YYYY-MM-DD or null",
  "timeline_note": "brief explanation of reasoning"
}
No markdown. No explanation outside the JSON.
"""


def _build_user_message(objective: str, teams: list, mode: str,
                         start_date: str, end_date: str) -> str:
    """Build the user message for mode B or C date estimation."""
    team_count = len(teams)
    if mode == "B":
        return (
            f"Project objective: {objective}\n"
            f"Number of teams: {team_count}\n"
            f"Start date: {start_date}\n"
            "The end date is unknown. Estimate a realistic end date based on the project scope and team size."
        )
    else:
        return (
            f"Project objective: {objective}\n"
            f"Number of teams: {team_count}\n"
            f"End date: {end_date}\n"
            "The start date is unknown. Reverse-engineer a realistic start date based on the project scope and team size."
        )


async def _call_haiku(user_message: str) -> DateResult:
    """Call Haiku and parse DateResult. Return empty DateResult on any error."""
    try:
        client = anthropic.AsyncAnthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
        response = await client.messages.create(
            model="claude-haiku-4-5-20251001",
            max_tokens=512,
            system=SYSTEM_PROMPT,
            messages=[{"role": "user", "content": user_message}],
        )
        text = response.content[0].text.strip()
        if text.startswith("```"):
            first_newline = text.find("\n")
            text = text[first_newline + 1:] if first_newline != -1 else text[3:]
            if text.rstrip().endswith("```"):
                text = text.rstrip()[:-3].rstrip()
        try:
            data = json.loads(text)
        except json.JSONDecodeError:
            data = repair_json(text, return_objects=True)
            if not isinstance(data, dict):
                data = {}
        return DateResult(**data)
    except anthropic.APITimeoutError:
        return DateResult()
    except anthropic.RateLimitError:
        return DateResult()
    except json.JSONDecodeError:
        return DateResult()
    except Exception:
        return DateResult()


async def run(objective: str, teams: list, start_date: str = "",
              end_date: str = "", start_ai: bool = False, end_ai: bool = False) -> DateResult:
    """
    Main entry point.
    Mode A: both user-provided -> return DateResult with those dates, no API call
    Mode B: start only -> estimate end via Haiku
    Mode C: end only -> reverse-engineer start via Haiku
    """
    try:
        mode = detect_date_mode(start=start_date, end=end_date,
                                start_ai=start_ai, end_ai=end_ai)
    except ValueError:
        return DateResult()

    if mode == "A":
        return DateResult(estimated_start_date=start_date, estimated_end_date=end_date)

    user_message = _build_user_message(objective, teams, mode, start_date, end_date)
    return await _call_haiku(user_message)