This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision Next revision | Previous revision | ||
|
язык_программирования_python [2026/11/18 12:20] val [tool_calling_demo.py] |
язык_программирования_python [2026/11/23 13:41] (current) val [tool_calling_demo.py] |
||
|---|---|---|---|
| Line 700: | Line 700: | ||
| # Начальный запрос пользователя | # Начальный запрос пользователя | ||
| - | user_query = "Привет! Назови мое счастливое число на сегодня и пожелай удачи разнообразно." | + | user_query = "Привет! Назови мое счастливое число на сегодня и пожелай удачи" |
| - | #user_query = "Привет! Пожелай мне удачи разнообразно." | + | # user_query = "Привет! Пожелай мне удачи" |
| messages = [ | messages = [ | ||
| Line 715: | Line 715: | ||
| ) | ) | ||
| - | response_message = response.choices[0].message | + | choice = response.choices[0] |
| + | response_message = choice.message | ||
| + | |||
| + | # --- ВЫВОД СЫРОГО ОТВЕТА МОДЕЛИ --- | ||
| + | print("\n--- Структура ответа модели (решение об инструменте) ---") | ||
| + | print(f"Причина остановки (finish_reason): {choice.finish_reason}") | ||
| + | print("Содержимое message (JSON):") | ||
| + | print(response_message.model_dump_json(indent=2, exclude_none=True)) | ||
| + | print("--------------------------------------------------------\n") | ||
| # Проверяем, решила ли модель вызвать инструмент | # Проверяем, решила ли модель вызвать инструмент | ||
| if response_message.tool_calls: | if response_message.tool_calls: | ||
| print("-> Агент запросил вызов инструмента.") | print("-> Агент запросил вызов инструмента.") | ||
| - | |||
| # Сохраняем ответ модели с запросом вызова функции в историю | # Сохраняем ответ модели с запросом вызова функции в историю | ||
| messages.append(response_message) | messages.append(response_message) | ||
| Line 728: | Line 735: | ||
| tool_result = get_random_lucky_number() | tool_result = get_random_lucky_number() | ||
| print(f"-> Результат локальной функции: {tool_result}") | print(f"-> Результат локальной функции: {tool_result}") | ||
| + | | ||
| # Возвращаем результат выполнения со специальной ролью "tool" | # Возвращаем результат выполнения со специальной ролью "tool" | ||
| messages.append({ | messages.append({ | ||
| Line 744: | Line 751: | ||
| temperature=0.7 | temperature=0.7 | ||
| ) | ) | ||
| - | |||
| print("\nИтоговый ответ AI агента:") | print("\nИтоговый ответ AI агента:") | ||
| print(final_response.choices[0].message.content) | print(final_response.choices[0].message.content) | ||
| - | |||
| else: | else: | ||
| - | print("\nОтвет модели:") | + | print("-> Инструмент не потребовался. Итоговый ответ модели:") |
| print(response_message.content) | print(response_message.content) | ||
| </code> | </code> | ||
| Line 758: | Line 763: | ||
| <code> | <code> | ||
| - | # export ZABBIX_TOKEN | + | $ export ZABBIX_TOKEN |
| + | |||
| + | (venv1) server:~$ pip install httpx mcp | ||
| </code><code> | </code><code> | ||
| import os | import os | ||
| Line 773: | Line 780: | ||
| ZABBIX_TOKEN = os.environ["ZABBIX_TOKEN"] | ZABBIX_TOKEN = os.environ["ZABBIX_TOKEN"] | ||
| MCP_URL = os.environ.get("MCP_SERVER_URL", "http://127.0.0.1:8080/mcp") | MCP_URL = os.environ.get("MCP_SERVER_URL", "http://127.0.0.1:8080/mcp") | ||
| + | |||
| + | |||
| + | def debug_log(title: str, data): | ||
| + | if hasattr(data, "model_dump"): | ||
| + | data = data.model_dump(exclude_none=True) | ||
| + | text = data if isinstance(data, str) else json.dumps(data, ensure_ascii=False, indent=2) | ||
| + | print(f"\n--- [DEBUG: {title}] ---\n{text}\n{'-' * (20 + len(title))}\n") | ||
| Line 800: | Line 814: | ||
| llm = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY, http_client=llm_http) | llm = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY, http_client=llm_http) | ||
| + | step = 1 | ||
| while True: | while True: | ||
| + | debug_log( | ||
| + | f"ШАГ {step} | ЗАПРОС К МОДЕЛИ", | ||
| + | [m.model_dump(exclude_none=True) if hasattr(m, "model_dump") else m for m in messages], | ||
| + | ) | ||
| + | |||
| resp = await llm.chat.completions.create( | resp = await llm.chat.completions.create( | ||
| model=MODEL_ID, | model=MODEL_ID, | ||
| Line 807: | Line 827: | ||
| temperature=0.1, | temperature=0.1, | ||
| ) | ) | ||
| + | |||
| + | debug_log(f"ШАГ {step} | ПОЛНЫЙ ОТВЕТ МОДЕЛИ", resp) | ||
| + | |||
| msg = resp.choices[0].message | msg = resp.choices[0].message | ||
| messages.append(msg) | messages.append(msg) | ||
| Line 815: | Line 838: | ||
| for tc in msg.tool_calls: | for tc in msg.tool_calls: | ||
| args = json.loads(tc.function.arguments or "{}") | args = json.loads(tc.function.arguments or "{}") | ||
| + | debug_log(f"ШАГ {step} | ВЫЗОВ ИНСТРУМЕНТА {tc.function.name}", args) | ||
| + | |||
| res = await session.call_tool(tc.function.name, arguments=args) | res = await session.call_tool(tc.function.name, arguments=args) | ||
| text = "\n".join(c.text for c in res.content if hasattr(c, "text")) | text = "\n".join(c.text for c in res.content if hasattr(c, "text")) | ||
| + | |||
| + | debug_log(f"ШАГ {step} | ОТВЕТ ИНСТРУМЕНТА {tc.function.name}", text or "Пустой ответ от инструмента") | ||
| + | |||
| messages.append({ | messages.append({ | ||
| "role": "tool", | "role": "tool", | ||
| Line 823: | Line 851: | ||
| "content": text or "Пустой ответ от инструмента", | "content": text or "Пустой ответ от инструмента", | ||
| }) | }) | ||
| + | |||
| + | step += 1 | ||
| + | |||
| if __name__ == "__main__": | if __name__ == "__main__": | ||