Spaces:
Running

File size: 1,681 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Plan-and-execute for compound operator requests.



The plan is fixed from the trusted operator request *before* any untrusted content is read,

and each step may only name a known chat-enabled intent. Steps then run one after another

through the normal subgraphs (and therefore through the gateway).

"""

from __future__ import annotations

from pydantic import BaseModel, Field

from core.agent.models import LLM
from core.packs.loader import IntentInfo

MAX_STEPS = 5


class PlanStep(BaseModel):
    intent: str
    instruction: str = Field(description="what this step should do, in one sentence")


class Plan(BaseModel):
    steps: list[PlanStep]


class PlanRejected(Exception):
    pass


def planner_prompt(intents: list[IntentInfo]) -> str:
    lines = "\n".join(f"- {i.name}: {i.description}" for i in intents if i.chat_enabled)
    return (
        "Break the business owner's request into an ordered list of steps. Each step must use "
        f"one of these intents:\n{lines}\n"
        f"Use at most {MAX_STEPS} steps. Do not invent intents."
    )


async def make_plan(request: str, intents: list[IntentInfo], llm: LLM) -> list[PlanStep]:
    plan = await llm.structured(Plan, planner_prompt(intents), request)
    allowed = {i.name for i in intents if i.chat_enabled}
    if not plan.steps:
        raise PlanRejected("empty plan")
    if len(plan.steps) > MAX_STEPS:
        raise PlanRejected(f"plan has {len(plan.steps)} steps, max {MAX_STEPS}")
    bad = [s.intent for s in plan.steps if s.intent not in allowed]
    if bad:
        raise PlanRejected(f"unknown intents in plan: {bad}")
    return plan.steps