Spaces:
Runtime error
Runtime error
| #!/usr/bin/env python3 | |
| """ | |
| Пример использования Grammar-based структурированного вывода | |
| Этот файл демонстрирует, как использовать новую функциональность грамматики | |
| в вашем приложении для точного контроля структуры JSON ответа. | |
| """ | |
| import json | |
| from typing import Dict, Any | |
| # Пример использования как в запросе пользователя | |
| def example_grammar_usage(): | |
| """ | |
| Демонстрация использования грамматики для структурированного вывода | |
| Аналогично примеру из запроса пользователя | |
| """ | |
| # JSON схема для профиля пользователя | |
| profile_schema = { | |
| "type": "object", | |
| "properties": { | |
| "name": {"type": "string"}, | |
| "age": {"type": "integer"}, | |
| "skills": { | |
| "type": "array", | |
| "items": {"type": "string"} | |
| }, | |
| "manager": {"type": "boolean"}, | |
| "projects": { | |
| "type": "array", | |
| "items": { | |
| "type": "object", | |
| "properties": { | |
| "name": {"type": "string"}, | |
| "budget": {"type": "number"} | |
| } | |
| } | |
| } | |
| }, | |
| "required": ["name", "age"] | |
| } | |
| prompt = "Return a profile for Alice, 29 y.o., Python and Rust, manager: false, projects: (Compiler, 120000.5) and (CLI, 5000)" | |
| print("🚀 Пример использования Grammar Mode") | |
| print("="*50) | |
| print(f"Промпт: {prompt}") | |
| print("\\nJSON Schema:") | |
| print(json.dumps(profile_schema, indent=2, ensure_ascii=False)) | |
| print("\\n📝 Как использовать в коде:") | |
| print(""" | |
| # Импорт необходимых модулей | |
| from llama_cpp import Llama, LlamaGrammar | |
| from app import _json_schema_to_gbnf, generate_structured_response | |
| # Пример вызова с грамматикой | |
| result = generate_structured_response( | |
| prompt=prompt, | |
| json_schema_str=json.dumps(profile_schema), | |
| use_grammar=True, # Включить Grammar Mode | |
| temperature=0.0, # Низкая температура для детерминированности | |
| ) | |
| print(result) | |
| """) | |
| def example_advanced_schemas(): | |
| """Примеры различных JSON схем для разных сценариев""" | |
| schemas = { | |
| "Анализ продуктов": { | |
| "type": "object", | |
| "properties": { | |
| "product_name": {"type": "string"}, | |
| "category": { | |
| "type": "string", | |
| "enum": ["electronics", "clothing", "books", "home"] | |
| }, | |
| "price": {"type": "number", "minimum": 0}, | |
| "rating": {"type": "number", "minimum": 1, "maximum": 5}, | |
| "features": { | |
| "type": "array", | |
| "items": {"type": "string"} | |
| }, | |
| "in_stock": {"type": "boolean"} | |
| }, | |
| "required": ["product_name", "category", "price"] | |
| }, | |
| "Медицинские данные": { | |
| "type": "object", | |
| "properties": { | |
| "patient_id": {"type": "string"}, | |
| "symptoms": { | |
| "type": "array", | |
| "items": {"type": "string"} | |
| }, | |
| "severity": { | |
| "type": "string", | |
| "enum": ["low", "medium", "high", "critical"] | |
| }, | |
| "vital_signs": { | |
| "type": "object", | |
| "properties": { | |
| "temperature": {"type": "number"}, | |
| "blood_pressure": {"type": "string"}, | |
| "heart_rate": {"type": "integer"} | |
| } | |
| }, | |
| "diagnosis": {"type": "string"} | |
| }, | |
| "required": ["patient_id", "symptoms", "severity"] | |
| }, | |
| "Финансовый отчет": { | |
| "type": "object", | |
| "properties": { | |
| "company": {"type": "string"}, | |
| "quarter": {"type": "string"}, | |
| "revenue": {"type": "number"}, | |
| "expenses": {"type": "number"}, | |
| "profit": {"type": "number"}, | |
| "departments": { | |
| "type": "array", | |
| "items": { | |
| "type": "object", | |
| "properties": { | |
| "name": {"type": "string"}, | |
| "budget": {"type": "number"}, | |
| "employees": {"type": "integer"} | |
| } | |
| } | |
| } | |
| }, | |
| "required": ["company", "quarter", "revenue", "expenses"] | |
| } | |
| } | |
| print("\\n🎯 Примеры продвинутых схем для разных сценариев:") | |
| print("="*60) | |
| for scenario, schema in schemas.items(): | |
| print(f"\\n📊 {scenario}:") | |
| print(json.dumps(schema, indent=2, ensure_ascii=False)) | |
| def example_gradio_interface(): | |
| """Пример использования в Gradio интерфейсе""" | |
| print("\\n🖥️ Использование в Gradio интерфейсе:") | |
| print("="*50) | |
| print(""" | |
| 1. Запустите приложение: python app.py | |
| 2. Откройте браузер и перейдите по адресу http://localhost:7860 | |
| 3. В интерфейсе вы увидите: | |
| - Поле для ввода промпта | |
| - Поле для JSON схемы | |
| - Чекбокс "🔗 Use Grammar (GBNF) Mode" | |
| - Кнопку "🚀 Generate Response" | |
| 4. Включите чекбокс Grammar Mode для: | |
| ✅ Точного соблюдения структуры JSON | |
| ✅ Гарантированного валидного JSON вывода | |
| ✅ Поддержки сложных вложенных структур | |
| ✅ Автоматической валидации енумов | |
| 5. Отключите Grammar Mode для: | |
| 🔄 Более гибкой генерации текста | |
| 🔄 Случаев, когда схема слишком сложная | |
| 🔄 Экспериментирования с промптами | |
| """) | |
| def main(): | |
| """Главная функция демонстрации""" | |
| example_grammar_usage() | |
| example_advanced_schemas() | |
| example_gradio_interface() | |
| print("\\n" + "="*60) | |
| print("🎉 Готово! Теперь вы можете использовать Grammar Mode") | |
| print(" для точного контроля структуры JSON ответов!") | |
| print("="*60) | |
| if __name__ == "__main__": | |
| main() | |