File size: 10,101 Bytes
6bedc74
 
2411e3d
6bedc74
 
 
 
 
 
2411e3d
 
6bedc74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2411e3d
6bedc74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2411e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bedc74
 
 
2411e3d
 
6bedc74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2411e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bedc74
2411e3d
 
 
 
 
6bedc74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2411e3d
6bedc74
 
 
 
 
 
2411e3d
 
 
 
 
 
 
6bedc74
2411e3d
 
 
 
 
6bedc74
2411e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bedc74
 
2411e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bedc74
2411e3d
 
 
6bedc74
 
 
 
 
 
 
 
 
 
2411e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6bedc74
 
 
 
 
 
2411e3d
 
 
 
 
6bedc74
 
 
 
 
2411e3d
6bedc74
 
 
 
 
 
 
 
2411e3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import json
import os
from collections.abc import Iterator
from typing import Any, Dict, List

from dotenv import load_dotenv
from openai import OpenAI

from src.audit import write_audit_record
from src.executor import authorize_tool_call, execute_authorized_tool
from src.schemas import AgentRunEvent, AgentRunResult, ToolCall
from src.tool_registry import get_tool_definitions


load_dotenv(dotenv_path=".env")


HF_BASE_URL = "https://router.huggingface.co/v1"
DEFAULT_MODEL = "openai/gpt-oss-120b:cerebras"

SYSTEM_PROMPT = """
You are a controlled tool-using operations agent.

You have access only to the tools explicitly provided to you.

Rules:
1. Use tools when they are needed to answer the user's request accurately.
2. Do not claim that a tool was used unless you actually called it.
3. Never invent tool results.
4. Do not invent tools that are not available.
5. Use the calculator for arithmetic rather than calculating mentally.
6. Use search_inventory for questions about the inventory database.
7. Use lookup_country for structured country information.
8. You may call multiple tools when the user's request requires them.
9. After receiving tool results, use those results to construct your answer.
10. If a tool is blocked or returns an error, do not hide the failure.
11. Do not expose internal chain-of-thought. Provide concise conclusions only.
"""


def get_client() -> OpenAI:
    """Create the Hugging Face OpenAI-compatible client."""

    token = os.getenv("HF_TOKEN")

    if not token:
        raise RuntimeError(
            "HF_TOKEN is not configured. "
            "Set it as an environment variable before running the agent."
        )

    return OpenAI(
        base_url=HF_BASE_URL,
        api_key=token,
    )


def _parse_tool_arguments(raw_arguments: str) -> Dict[str, Any]:
    """Decode model-provided tool arguments into an object for validation."""

    try:
        arguments = json.loads(raw_arguments)

        if not isinstance(arguments, dict):
            raise ValueError(
                "Tool arguments must decode to an object."
            )

        return arguments

    except (json.JSONDecodeError, ValueError):
        return {
            "__invalid_arguments__": raw_arguments,
        }


def run_agent_iter(
    user_request: str,
    model: str | None = None,
    max_tool_rounds: int = 5,
) -> Iterator[AgentRunEvent]:
    """Run the agent while emitting real control-boundary events."""

    if not isinstance(user_request, str):
        raise TypeError("user_request must be a string.")

    user_request = user_request.strip()

    if not user_request:
        raise ValueError("user_request cannot be empty.")

    if max_tool_rounds < 1:
        raise ValueError(
            "max_tool_rounds must be at least 1."
        )

    client = get_client()

    selected_model = (
        model
        or os.getenv("MODEL_ID")
        or DEFAULT_MODEL
    )

    tools = get_tool_definitions()

    messages: List[Dict[str, Any]] = [
        {
            "role": "system",
            "content": SYSTEM_PROMPT,
        },
        {
            "role": "user",
            "content": user_request,
        },
    ]

    executed_calls: List[ToolCall] = []
    executed_results = []

    yield AgentRunEvent(
        event="run_started",
        message=(
            "Request accepted. The model may propose only tools exposed "
            "through the approved registry."
        ),
    )

    for round_index in range(1, max_tool_rounds + 1):
        yield AgentRunEvent(
            event="model_thinking",
            round_index=round_index,
            message="The model is deciding whether an approved tool is needed.",
        )

        response = client.chat.completions.create(
            model=selected_model,
            messages=messages,
            tools=tools,
            tool_choice="auto",
            reasoning_effort="low",
        )

        message = response.choices[0].message

        assistant_message: Dict[str, Any] = {
            "role": "assistant",
            "content": message.content,
        }

        if message.tool_calls:
            assistant_message["tool_calls"] = [
                tool_call.model_dump()
                for tool_call in message.tool_calls
            ]

        messages.append(assistant_message)

        if not message.tool_calls:
            final_answer = (
                message.content
                or "The agent returned no final answer."
            )

            final_result = AgentRunResult(
                user_request=user_request,
                final_answer=final_answer,
                tool_calls=executed_calls,
                tool_results=executed_results,
            )

            yield AgentRunEvent(
                event="final_answer",
                round_index=round_index,
                message="The model produced the final answer from the available results.",
                final_result=final_result,
            )
            return

        for model_tool_call in message.tool_calls:
            call = ToolCall(
                call_id=model_tool_call.id,
                tool_name=model_tool_call.function.name,
                arguments=_parse_tool_arguments(
                    model_tool_call.function.arguments
                ),
            )

            yield AgentRunEvent(
                event="tool_requested",
                round_index=round_index,
                message=f"The model requested the '{call.tool_name}' tool.",
                call=call,
            )

            authorization = authorize_tool_call(call)

            if authorization.status == "approved":
                yield AgentRunEvent(
                    event="tool_approved",
                    round_index=round_index,
                    message=(
                        f"Application approved '{call.tool_name}': "
                        f"{authorization.reason}"
                    ),
                    call=call,
                    authorization=authorization,
                )
            else:
                result = execute_authorized_tool(
                    call=call,
                    authorization=authorization,
                )
                write_audit_record(call=call, result=result)
                executed_calls.append(call)
                executed_results.append(result)

                yield AgentRunEvent(
                    event="tool_blocked",
                    round_index=round_index,
                    message=(
                        f"Application blocked '{call.tool_name}' before execution: "
                        f"{authorization.reason}"
                    ),
                    call=call,
                    authorization=authorization,
                    result=result,
                )

                messages.append(
                    {
                        "role": "tool",
                        "tool_call_id": model_tool_call.id,
                        "content": json.dumps(
                            {
                                "status": result.status,
                                "output": result.output,
                                "error": result.error,
                            },
                            default=str,
                        ),
                    }
                )
                continue

            result = execute_authorized_tool(
                call=call,
                authorization=authorization,
            )

            write_audit_record(
                call=call,
                result=result,
            )

            executed_calls.append(call)
            executed_results.append(result)

            event_name = (
                "tool_succeeded"
                if result.status == "success"
                else "tool_failed"
            )

            event_message = (
                f"Approved tool '{call.tool_name}' executed successfully."
                if result.status == "success"
                else (
                    f"Approved tool '{call.tool_name}' failed during execution: "
                    f"{result.error}"
                )
            )

            yield AgentRunEvent(
                event=event_name,
                round_index=round_index,
                message=event_message,
                call=call,
                authorization=authorization,
                result=result,
            )

            messages.append(
                {
                    "role": "tool",
                    "tool_call_id": model_tool_call.id,
                    "content": json.dumps(
                        {
                            "status": result.status,
                            "output": result.output,
                            "error": result.error,
                        },
                        default=str,
                    ),
                }
            )

    final_result = AgentRunResult(
        user_request=user_request,
        final_answer=(
            "The agent reached the maximum number "
            "of tool-execution rounds before producing "
            "a final answer."
        ),
        tool_calls=executed_calls,
        tool_results=executed_results,
    )

    yield AgentRunEvent(
        event="max_rounds_reached",
        round_index=max_tool_rounds,
        message="The configured tool-round limit was reached.",
        final_result=final_result,
    )


def run_agent(
    user_request: str,
    model: str | None = None,
    max_tool_rounds: int = 5,
) -> AgentRunResult:
    """Run the tool-using agent and return the final structured result."""

    final_result: AgentRunResult | None = None

    for event in run_agent_iter(
        user_request=user_request,
        model=model,
        max_tool_rounds=max_tool_rounds,
    ):
        if event.final_result is not None:
            final_result = event.final_result

    if final_result is None:
        raise RuntimeError(
            "Agent run ended without a final result."
        )

    return final_result