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 10:36] val [openai_request_to_llm.py] |
язык_программирования_python [2026/11/23 13:41] (current) val [tool_calling_demo.py] |
||
|---|---|---|---|
| Line 567: | Line 567: | ||
| </code> | </code> | ||
| или | или | ||
| - | </code> | + | <code> |
| # apt install python3-openai | # apt install python3-openai | ||
| </code> | </code> | ||
| Line 700: | Line 700: | ||
| # Начальный запрос пользователя | # Начальный запрос пользователя | ||
| + | user_query = "Привет! Назови мое счастливое число на сегодня и пожелай удачи" | ||
| + | # user_query = "Привет! Пожелай мне удачи" | ||
| + | |||
| messages = [ | messages = [ | ||
| - | {"role": "user", "content": "Привет! Назови мое счастливое число на сегодня и пожелай удачи разнообразно."} | + | {"role": "user", "content": user_query} |
| ] | ] | ||
| Line 712: | 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 725: | 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 741: | 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> | ||
| + | |||
| + | ==== zabbix_ai.py ==== | ||
| + | |||
| + | * [[#openai_request_to_llm.py]] | ||
| + | |||
| + | <code> | ||
| + | $ export ZABBIX_TOKEN | ||
| + | |||
| + | (venv1) server:~$ pip install httpx mcp | ||
| + | </code><code> | ||
| + | import os | ||
| + | import json | ||
| + | import asyncio | ||
| + | import httpx | ||
| + | from openai import AsyncOpenAI | ||
| + | from mcp import ClientSession | ||
| + | from mcp.client.streamable_http import streamable_http_client | ||
| + | |||
| + | BASE_URL = os.environ["BASE_URL"] | ||
| + | API_KEY = os.environ["API_KEY"] | ||
| + | MODEL_ID = os.environ["MODEL_ID"] | ||
| + | ZABBIX_TOKEN = os.environ["ZABBIX_TOKEN"] | ||
| + | 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") | ||
| + | |||
| + | |||
| + | async def ask(messages: list) -> str: | ||
| + | headers = {"Authorization": f"Bearer {ZABBIX_TOKEN}"} | ||
| + | |||
| + | async with ( | ||
| + | httpx.AsyncClient(headers=headers) as mcp_http, | ||
| + | httpx.AsyncClient(timeout=120.0) as llm_http, | ||
| + | streamable_http_client(MCP_URL, http_client=mcp_http) as (read, write), | ||
| + | ClientSession(read, write) as session, | ||
| + | ): | ||
| + | await session.initialize() | ||
| + | tools_res = await session.list_tools() | ||
| + | tools = [ | ||
| + | { | ||
| + | "type": "function", | ||
| + | "function": { | ||
| + | "name": t.name, | ||
| + | "description": t.description or "", | ||
| + | "parameters": t.input_schema, | ||
| + | }, | ||
| + | } | ||
| + | for t in tools_res.tools | ||
| + | ] | ||
| + | |||
| + | llm = AsyncOpenAI(base_url=BASE_URL, api_key=API_KEY, http_client=llm_http) | ||
| + | |||
| + | step = 1 | ||
| + | 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( | ||
| + | model=MODEL_ID, | ||
| + | messages=messages, | ||
| + | tools=tools or None, | ||
| + | temperature=0.1, | ||
| + | ) | ||
| + | |||
| + | debug_log(f"ШАГ {step} | ПОЛНЫЙ ОТВЕТ МОДЕЛИ", resp) | ||
| + | |||
| + | msg = resp.choices[0].message | ||
| + | messages.append(msg) | ||
| + | |||
| + | if not msg.tool_calls: | ||
| + | return msg.content or "" | ||
| + | |||
| + | for tc in msg.tool_calls: | ||
| + | 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) | ||
| + | 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({ | ||
| + | "role": "tool", | ||
| + | "tool_call_id": tc.id, | ||
| + | "name": tc.function.name, | ||
| + | "content": text or "Пустой ответ от инструмента", | ||
| + | }) | ||
| + | |||
| + | step += 1 | ||
| + | |||
| + | |||
| + | if __name__ == "__main__": | ||
| + | messages = [{"role": "system", "content": "Ты помощник Zabbix. Отвечай кратко и по делу."}] | ||
| + | print("Чат с Zabbix AI запущен (Ctrl+C для выхода).\n") | ||
| + | |||
| + | while True: | ||
| + | try: | ||
| + | user_input = input("Вы: ").strip() | ||
| + | if not user_input: | ||
| + | continue | ||
| + | |||
| + | messages.append({"role": "user", "content": user_input}) | ||
| + | answer = asyncio.run(ask(messages)) | ||
| + | print(f"\nАссистент:\n{answer}\n") | ||
| + | |||
| + | except (KeyboardInterrupt, EOFError): | ||
| + | print("\nВыход.") | ||
| + | break | ||
| </code> | </code> | ||
| ==== ari_echo_talk_detect.py ==== | ==== ari_echo_talk_detect.py ==== | ||