File size: 9,926 Bytes
58f6928
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
from typing import Any

from llm_client import LLMClient
from prompts import SYSTEM_PROMPT
from tool_schemas import get_tool_schemas
from tools import execute_tool


class BookstoreAgent:
    """
    Kullanıcı mesajını modele gönderir, tool çağrılarını çalıştırır
    ve veritabanı sonucuna dayalı nihai cevabı üretir.
    """

    def __init__(
        self,
        *,
        model_id: str | None = None,
        max_tool_iterations: int = 6,
    ) -> None:
        self.llm_client = LLMClient(model_id=model_id)
        self.tool_schemas = get_tool_schemas(strict=False)
        self.max_tool_iterations = max_tool_iterations

    @staticmethod
    def parse_tool_arguments(
        raw_arguments: Any,
    ) -> dict[str, Any]:
        """
        Farklı inference sağlayıcılarından gelebilecek tool
        argümanlarını güvenli biçimde sözlüğe dönüştürür.
        """

        if isinstance(raw_arguments, dict):
            return raw_arguments

        if isinstance(raw_arguments, str):
            try:
                parsed_arguments = json.loads(raw_arguments)
            except json.JSONDecodeError as error:
                raise ValueError(
                    "Model geçerli JSON tool parametresi üretmedi."
                ) from error

            if not isinstance(parsed_arguments, dict):
                raise ValueError(
                    "Tool parametrelerinin JSON nesnesi olması gerekiyor."
                )

            return parsed_arguments

        raise ValueError(
            "Tool parametreleri desteklenmeyen bir biçimde geldi."
        )

    @staticmethod
    def prepare_history(
        history: list[dict[str, str]] | None,
    ) -> list[dict[str, str]]:
        """
        Önceki konuşmadan yalnızca user ve assistant mesajlarını alır.
        """

        prepared_messages: list[dict[str, str]] = []

        if not history:
            return prepared_messages

        # Çok uzun konuşmaların API isteğini şişirmemesi için
        # yalnızca son 12 mesajı kullanıyoruz.
        for message in history[-12:]:
            role = message.get("role")
            content = message.get("content", "")

            if role not in {"user", "assistant"}:
                continue

            if not isinstance(content, str):
                continue

            prepared_messages.append(
                {
                    "role": role,
                    "content": content,
                }
            )

        return prepared_messages

    def run(
        self,
        user_message: str,
        history: list[dict[str, str]] | None = None,
    ) -> dict[str, Any]:
        """
        Tek bir kullanıcı isteğini uçtan uca işler.

        Dönüş:
        {
            "success": bool,
            "answer": str,
            "tool_logs": [...]
        }
        """

        user_message = user_message.strip()

        if not user_message:
            return {
                "success": False,
                "answer": "Lütfen bir mesaj yazın.",
                "tool_logs": [],
            }

        messages: list[Any] = [
            {
                "role": "system",
                "content": SYSTEM_PROMPT,
            }
        ]

        messages.extend(self.prepare_history(history))

        messages.append(
            {
                "role": "user",
                "content": user_message,
            }
        )

        tool_logs: list[dict[str, Any]] = []

        # create_order yalnızca bu turda search_books tarafından
        # döndürülmüş gerçek book_id değerlerini kullanabilir.
        authorized_book_ids: set[int] = set()

        # Model aynı kullanıcı mesajında yanlışlıkla ikinci kez
        # sipariş oluşturmasın.
        order_created_in_this_turn = False

        for iteration in range(1, self.max_tool_iterations + 1):
            response = self.llm_client.create_chat_completion(
                messages,
                tools=self.tool_schemas,
                tool_choice="auto",
            )

            if not response.choices:
                return {
                    "success": False,
                    "answer": "Model boş bir cevap döndürdü.",
                    "tool_logs": tool_logs,
                }

            response_message = response.choices[0].message
            tool_calls = getattr(
                response_message,
                "tool_calls",
                None,
            )

            # Tool çağrısı yoksa bu, kullanıcıya verilecek nihai cevaptır.
            if not tool_calls:
                answer = getattr(
                    response_message,
                    "content",
                    None,
                )

                if not answer:
                    answer = (
                        "İşlem tamamlandı ancak model metin cevabı "
                        "oluşturmadı."
                    )

                return {
                    "success": True,
                    "answer": str(answer).strip(),
                    "tool_logs": tool_logs,
                    "iterations": iteration,
                }

            # Resmî HF akışında assistant tool-call mesajı,
            # tool sonuçlarından önce konuşmaya eklenir.
            messages.append(response_message)

            for tool_call in tool_calls:
                tool_name = tool_call.function.name
                raw_arguments = tool_call.function.arguments

                try:
                    arguments = self.parse_tool_arguments(
                        raw_arguments
                    )
                except ValueError as error:
                    arguments = {}

                    tool_result = {
                        "success": False,
                        "error": str(error),
                    }
                else:
                    # Modelin book_id uydurmasını kesin olarak engelle.
                    if tool_name == "create_order":
                        requested_book_id = arguments.get("book_id")

                        if order_created_in_this_turn:
                            tool_result = {
                                "success": False,
                                "error": (
                                    "Bu kullanıcı isteği için zaten bir "
                                    "sipariş oluşturuldu. İkinci sipariş "
                                    "oluşturulmadı."
                                ),
                            }

                        elif requested_book_id not in authorized_book_ids:
                            tool_result = {
                                "success": False,
                                "error": (
                                    "create_order çağrısından önce "
                                    "search_books kullanılmalı ve book_id "
                                    "o tool sonucundan alınmalıdır."
                                ),
                                "requested_book_id": requested_book_id,
                            }

                        else:
                            tool_result = execute_tool(
                                tool_name,
                                arguments,
                            )

                    else:
                        tool_result = execute_tool(
                            tool_name,
                            arguments,
                        )

                # Başarılı arama sonucundaki gerçek kitap ID'lerini kaydet.
                if (
                    tool_name == "search_books"
                    and tool_result.get("success") is True
                ):
                    for book in tool_result.get("books", []):
                        book_id = book.get("book_id")

                        if isinstance(book_id, int):
                            authorized_book_ids.add(book_id)

                if (
                    tool_name == "create_order"
                    and tool_result.get("success") is True
                ):
                    order_created_in_this_turn = True

                log_entry = {
                    "iteration": iteration,
                    "tool_call_id": tool_call.id,
                    "tool_name": tool_name,
                    "arguments": arguments,
                    "result": tool_result,
                }

                tool_logs.append(log_entry)

                print("\n" + "=" * 80)
                print(f"TOOL CALL: {tool_name}")
                print("=" * 80)
                print(
                    "Arguments:",
                    json.dumps(
                        arguments,
                        ensure_ascii=False,
                        indent=2,
                    ),
                )
                print(
                    "Result:",
                    json.dumps(
                        tool_result,
                        ensure_ascii=False,
                        indent=2,
                    ),
                )

                # Tool sonucunu yeniden modele gönderiyoruz.
                messages.append(
                    {
                        "tool_call_id": tool_call.id,
                        "role": "tool",
                        "name": tool_name,
                        "content": json.dumps(
                            tool_result,
                            ensure_ascii=False,
                        ),
                    }
                )

        return {
            "success": False,
            "answer": (
                "İşlem güvenlik sınırına ulaştığı için durduruldu. "
                "Lütfen isteğinizi daha açık biçimde tekrar yazın."
            ),
            "tool_logs": tool_logs,
            "iterations": self.max_tool_iterations,
        }