Guest User

Untitled

a guest
Mar 10th, 2026
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.58 KB | None | 0 0
  1. import json
  2. from openai import OpenAI
  3.  
  4. # ==========================================
  5. # 1. Настройки API (задаются здесь)
  6. # ==========================================
  7. API_KEY = "sk-your-api-key-here"
  8. # Оставьте BASE_URL по умолчанию для OpenAI, или замените на свой (например, для локального сервера LM Studio / vLLM)
  9. BASE_URL = "http://127.0.0.1:8000/v1"
  10. MODEL = "model_name"
  11.  
  12. # Инициализируем клиента
  13. client = OpenAI(
  14. api_key=API_KEY,
  15. base_url=BASE_URL
  16. )
  17.  
  18. # ==========================================
  19. # 2. Определяем инструменты
  20. # ==========================================
  21. tools = [
  22. {
  23. "type": "function",
  24. "function": {
  25. "name": "get_current_weather",
  26. "description": "Получает текущую погоду в заданном городе",
  27. "parameters": {
  28. "type": "object",
  29. "properties": {
  30. "location": {"type": "string", "description": "Город и страна, например: Токио, Япония"}
  31. },
  32. "required": ["location"]
  33. }
  34. }
  35. },
  36. {
  37. "type": "function",
  38. "function": {
  39. "name": "get_current_time",
  40. "description": "Получает текущее время для указанного региона",
  41. "parameters": {
  42. "type": "object",
  43. "properties": {
  44. "timezone": {"type": "string", "description": "Таймзона, например: Asia/Tokyo"}
  45. },
  46. "required": ["timezone"]
  47. }
  48. }
  49. }
  50. ]
  51.  
  52. # ==========================================
  53. # 3. Отправляем запрос и логируем результат
  54. # ==========================================
  55. def test_openai_function_calling():
  56. print(f"🚀 Отправляем запрос через библиотеку OpenAI (Модель: {MODEL})...")
  57.  
  58. messages = [
  59. {"role": "user", "content": "Какая сейчас погода в Токио и сколько там времени?"}
  60. ]
  61.  
  62. try:
  63. response = client.chat.completions.create(
  64. model=MODEL,
  65. messages=messages,
  66. tools=tools,
  67. tool_choice="auto"
  68. )
  69.  
  70. # В библиотеке openai мы обращаемся к атрибутам через точку
  71. choice = response.choices[0]
  72. message = choice.message
  73. finish_reason = choice.finish_reason
  74.  
  75. print("\n--- ЛОГ ОТВЕТА ---")
  76.  
  77. # 1. Проверяем наличие текстового ответа (комментарии модели)
  78. if message.content:
  79. print(f"💬 Текстовый ответ модели: {message.content}")
  80. else:
  81. print("💬 Текстовый ответ отсутствует (модель сразу перешла к вызовам).")
  82.  
  83. # 2. Проверяем наличие вызовов функций
  84. if finish_reason == "tool_calls" and message.tool_calls:
  85. print("\n✅ УСПЕХ: Модель запросила вызов функций!")
  86. print(f"Количество запрошенных функций: {len(message.tool_calls)}")
  87.  
  88. for index, tool_call in enumerate(message.tool_calls, start=1):
  89. func_name = tool_call.function.name
  90. func_args = tool_call.function.arguments
  91.  
  92. print(f" [{index}] Функция: '{func_name}'")
  93. print(f" Аргументы: {func_args}")
  94.  
  95. # Проверка валидности JSON в аргументах
  96. try:
  97. json.loads(func_args)
  98. print(" Статус аргументов: Валидный JSON 🟢")
  99. except json.JSONDecodeError:
  100. print(" Статус аргументов: ОШИБКА парсинга JSON 🔴")
  101.  
  102. else:
  103. print(f"\n❌ НЕУДАЧА: Модель не вызвала функции. Причина завершения: {finish_reason}")
  104.  
  105. except Exception as e:
  106. print(f"\n🔴 ОШИБКА API: {e}")
  107.  
  108. if __name__ == "__main__":
  109. test_openai_function_calling()
Advertisement
Add Comment
Please, Sign In to add comment