File size: 3,133 Bytes
e5dfbda
 
 
f346c47
 
d3642af
e5dfbda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f346c47
e5dfbda
 
 
 
 
 
 
d3642af
f346c47
 
 
 
 
e5dfbda
f346c47
 
 
e5dfbda
d3642af
e5dfbda
 
1f505c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e5dfbda
 
 
d3642af
e5dfbda
d3642af
 
e5dfbda
d3642af
e5dfbda
d3642af
 
 
 
 
 
e5dfbda
 
d3642af
e5dfbda
 
d3642af
 
e5dfbda
 
 
 
 
 
 
d3642af
e5dfbda
 
d3642af
 
 
 
 
e5dfbda
 
d3642af
f346c47
e5dfbda
d3642af
e5dfbda
f346c47
d3642af
 
 
 
 
 
 
f346c47
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import uuid
import yaml

from agentctl.agent import K8sAgent
from agentctl.config import settings
from agentctl.llm import ask_llm, HF_MODEL  # <--- import model name


def randomize_name(yaml_text: str) -> str:
    try:
        obj = yaml.safe_load(yaml_text)
        if not isinstance(obj, dict):
            return yaml_text

        kind = obj.get("kind")
        if kind not in ("Job", "Deployment", "CronJob"):
            return yaml_text

        metadata = obj.setdefault("metadata", {})
        name = metadata.get("name")
        if not name:
            return yaml_text

        suffix = str(uuid.uuid4())[:5]
        metadata["name"] = f"{name}-{suffix}"

        return yaml.dump(obj, sort_keys=False)

    except Exception:
        return yaml_text
    

class AgentService:
    def __init__(self):
        self.agent = K8sAgent()

    async def generate_yaml(self, prompt: str, namespace: str | None, kind: str | None):
        ns = namespace or settings.k8s_namespace
        kind_sel = None if (kind is None or kind == "Auto") else kind

        # -------------------------------
        # 1) LLM PLAN STEP
        # -------------------------------
        plan_prompt = f"""
            Convert this plan into valid Kubernetes YAML.
            HARD RULES:
            - kind: Job
            - image: busybox or python:3.10-slim only
            - restartPolicy: Never
            - No GPUs, no ML, no training.
            - Commands MUST be simple (echo/sleep/ls)
            - No markdown
            - No commentary

            Plan:
            {prompt}
            Output:
            - workload type
            - image
            - command
            - args
            """


        try:
            plan = await ask_llm(plan_prompt)

        except Exception as e:
            print(f"[LLM ERROR: plan] Fallback. Error: {e}")

            _, yaml_text = self.agent.nl_to_resource_yaml(
                prompt, namespace=ns, kind=kind_sel
            )

            return {
                "yaml": randomize_name(yaml_text),
                "mode": "fallback",
                "model": None
            }

        # -------------------------------
        # 2) LLM YAML STEP
        # -------------------------------
        yaml_prompt = f"""
        Convert this Kubernetes plan into valid Kubernetes YAML.
        Output ONLY YAML:

        {plan}
        """

        try:
            yaml_text = await ask_llm(yaml_prompt)

            if not yaml_text or yaml_text.strip() == "":
                raise ValueError("Empty YAML from LLM")

            return {
                "yaml": randomize_name(yaml_text),
                "mode": "llm",
                "model": HF_MODEL
            }

        except Exception as e:
            print(f"[LLM ERROR: yaml] Fallback. Error: {e}")

            _, yaml_text = self.agent.nl_to_resource_yaml(
                prompt, namespace=ns, kind=kind_sel
            )

            return {
                "yaml": randomize_name(yaml_text),
                "mode": "fallback",
                "model": None
            }


agent_service = AgentService()