| """
|
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| β β
|
| β QUICK INTEGRATION EXAMPLE FOR app.py β
|
| β Drop-in integration der neuen Conversation Systems β
|
| β β
|
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
| This file shows exactly how to integrate the new conversation system into app.py
|
| """
|
|
|
|
|
|
|
|
|
|
|
| """
|
| from training_data_loader import SituationalResponseGenerator
|
|
|
| # In your Flask app __init__:
|
| response_generator = SituationalResponseGenerator()
|
|
|
| # In your chat route (replace old response generation):
|
| @app.route('/api/chat', methods=['POST'])
|
| def chat():
|
| message = request.json.get('message')
|
|
|
| # OLD: response = old_response_generator(message)
|
|
|
| # NEW: One line!
|
| response = response_generator.generate(message, turn_count=1, topic="general")
|
|
|
| return jsonify({'response': response})
|
| """
|
|
|
|
|
|
|
|
|
|
|
| """
|
| from advanced_conversation_manager import AdvancedConversationManager
|
| from training_data_loader import SituationalResponseGenerator
|
|
|
| class SmartChatIntegration:
|
| def __init__(self):
|
| self.manager = AdvancedConversationManager()
|
| self.generator = SituationalResponseGenerator()
|
| self.active_dialogs = {} # Track active conversations
|
|
|
| def start_conversation(self, user_id, initial_message):
|
| '''Start new conversation'''
|
| response, dialog = self.manager.start_dialog(user_id, initial_message)
|
|
|
| # Save reference
|
| self.active_dialogs[dialog.dialog_id] = dialog
|
|
|
| return {
|
| 'response': response,
|
| 'dialog_id': dialog.dialog_id,
|
| 'turn': 1
|
| }
|
|
|
| def continue_conversation(self, dialog_id, user_message):
|
| '''Continue existing conversation'''
|
| dialog = self.active_dialogs.get(dialog_id)
|
|
|
| if not dialog:
|
| # If not found, start new dialog
|
| return self.start_conversation("unknown", user_message)
|
|
|
| response, updated_dialog = self.manager.continue_dialog(
|
| dialog_id,
|
| user_message
|
| )
|
|
|
| # Update reference
|
| self.active_dialogs[dialog_id] = updated_dialog
|
|
|
| return {
|
| 'response': response,
|
| 'dialog_id': dialog_id,
|
| 'turn': len(updated_dialog.turns),
|
| 'context': self.manager.understand_context(updated_dialog)
|
| }
|
|
|
| # In app.py:
|
| app = Flask(__name__)
|
| chat_integration = SmartChatIntegration()
|
|
|
| @app.route('/api/chat/start', methods=['POST'])
|
| def start_chat():
|
| data = request.json
|
| user_id = data.get('user_id', 'anonymous')
|
| message = data.get('message', 'Hallo')
|
|
|
| result = chat_integration.start_conversation(user_id, message)
|
| return jsonify(result)
|
|
|
| @app.route('/api/chat/continue', methods=['POST'])
|
| def continue_chat():
|
| data = request.json
|
| dialog_id = data.get('dialog_id')
|
| message = data.get('message')
|
|
|
| if not dialog_id:
|
| return jsonify({'error': 'missing dialog_id'}), 400
|
|
|
| result = chat_integration.continue_conversation(dialog_id, message)
|
| return jsonify(result)
|
|
|
| @app.route('/api/chat/summary/<dialog_id>', methods=['GET'])
|
| def get_summary(dialog_id):
|
| summary = chat_integration.manager.get_dialog_summary(dialog_id)
|
| return jsonify({'summary': summary})
|
| """
|
|
|
|
|
|
|
|
|
|
|
| """
|
| # Imports
|
| from training_data_loader import SituationalResponseGenerator
|
| from advanced_conversation_manager import AdvancedConversationManager
|
|
|
| # Initialize at app startup
|
| app = Flask(__name__)
|
|
|
| # Keep old system
|
| OLD_RESPONSE_SYSTEM = your_old_response_generator()
|
|
|
| # Add new conversation system
|
| NEW_CONVERSATION_SYSTEM = AdvancedConversationManager()
|
| RESPONSE_GENERATOR = SituationalResponseGenerator()
|
|
|
| @app.route('/api/chat', methods=['POST'])
|
| def chat():
|
| data = request.json
|
| message = data.get('message')
|
| dialog_id = data.get('dialog_id')
|
| use_new_system = data.get('use_new_system', True) # Can switch
|
|
|
| if use_new_system and dialog_id:
|
| # Use NEW conversation system for multi-turn
|
| response, dialog = NEW_CONVERSATION_SYSTEM.continue_dialog(
|
| dialog_id,
|
| message
|
| )
|
| elif use_new_system:
|
| # Start NEW conversation
|
| response, dialog = NEW_CONVERSATION_SYSTEM.start_dialog(
|
| data.get('user_id', 'anon'),
|
| message
|
| )
|
| dialog_id = dialog.dialog_id
|
| else:
|
| # Fallback to OLD system
|
| response = OLD_RESPONSE_SYSTEM.generate_response(message)
|
| dialog_id = None
|
|
|
| return jsonify({
|
| 'response': response,
|
| 'dialog_id': dialog_id
|
| })
|
| """
|
|
|
|
|
|
|
|
|
|
|
| from flask import Flask, request, jsonify, render_template
|
| from advanced_conversation_manager import AdvancedConversationManager
|
| from training_data_loader import SituationalResponseGenerator
|
| import json
|
| from datetime import datetime
|
|
|
| app = Flask(__name__)
|
|
|
|
|
| conversation_manager = AdvancedConversationManager()
|
| response_generator = SituationalResponseGenerator()
|
|
|
|
|
| active_dialogs = {}
|
|
|
|
|
|
|
|
|
|
|
| @app.route('/api/chat/new', methods=['POST'])
|
| def start_new_conversation():
|
| """Start a new conversation"""
|
| data = request.json
|
| user_id = data.get('user_id', 'anonymous')
|
| user_message = data.get('message', '')
|
|
|
| if not user_message:
|
| return jsonify({'error': 'message required'}), 400
|
|
|
| try:
|
| response, dialog = conversation_manager.start_dialog(
|
| user_id,
|
| user_message
|
| )
|
|
|
|
|
| active_dialogs[dialog.dialog_id] = {
|
| 'dialog': dialog,
|
| 'created_at': datetime.now().isoformat(),
|
| 'user_id': user_id
|
| }
|
|
|
| return jsonify({
|
| 'success': True,
|
| 'dialog_id': dialog.dialog_id,
|
| 'response': response,
|
| 'turn': 1,
|
| 'user_id': user_id
|
| })
|
|
|
| except Exception as e:
|
| return jsonify({'error': str(e)}), 500
|
|
|
|
|
| @app.route('/api/chat/continue', methods=['POST'])
|
| def continue_conversation():
|
| """Continue an existing conversation"""
|
| data = request.json
|
| dialog_id = data.get('dialog_id')
|
| user_message = data.get('message', '')
|
|
|
| if not dialog_id or not user_message:
|
| return jsonify({'error': 'dialog_id and message required'}), 400
|
|
|
| dialog_data = active_dialogs.get(dialog_id)
|
|
|
| if not dialog_data:
|
| return jsonify({'error': f'dialog_id not found: {dialog_id}'}), 404
|
|
|
| try:
|
| response, updated_dialog = conversation_manager.continue_dialog(
|
| dialog_id,
|
| user_message
|
| )
|
|
|
|
|
| active_dialogs[dialog_id]['dialog'] = updated_dialog
|
|
|
|
|
| context = conversation_manager.understand_context(updated_dialog)
|
|
|
| return jsonify({
|
| 'success': True,
|
| 'dialog_id': dialog_id,
|
| 'response': response,
|
| 'turn': len(updated_dialog.turns),
|
| 'context': {
|
| 'topics': context.get('current_topics', []),
|
| 'user_expertise': context.get('user_expertise', {}),
|
| 'confirmed_facts': context.get('confirmed_facts', [])
|
| }
|
| })
|
|
|
| except Exception as e:
|
| return jsonify({'error': str(e)}), 500
|
|
|
|
|
| @app.route('/api/chat/summary/<dialog_id>', methods=['GET'])
|
| def get_conversation_summary(dialog_id):
|
| """Get summary of a conversation"""
|
| dialog_data = active_dialogs.get(dialog_id)
|
|
|
| if not dialog_data:
|
| return jsonify({'error': f'dialog_id not found: {dialog_id}'}), 404
|
|
|
| try:
|
| summary = conversation_manager.get_dialog_summary(dialog_id)
|
|
|
| return jsonify({
|
| 'success': True,
|
| 'dialog_id': dialog_id,
|
| 'summary': summary,
|
| 'turn_count': len(dialog_data['dialog'].turns),
|
| 'user_id': dialog_data['user_id'],
|
| 'created_at': dialog_data['created_at']
|
| })
|
|
|
| except Exception as e:
|
| return jsonify({'error': str(e)}), 500
|
|
|
|
|
| @app.route('/api/chat/conversations', methods=['GET'])
|
| def list_conversations():
|
| """List all active conversations"""
|
| user_id = request.args.get('user_id')
|
|
|
| convs = []
|
| for dialog_id, data in active_dialogs.items():
|
| if user_id is None or data['user_id'] == user_id:
|
| convs.append({
|
| 'dialog_id': dialog_id,
|
| 'user_id': data['user_id'],
|
| 'turns': len(data['dialog'].turns),
|
| 'created_at': data['created_at']
|
| })
|
|
|
| return jsonify({
|
| 'success': True,
|
| 'conversations': convs,
|
| 'count': len(convs)
|
| })
|
|
|
|
|
| @app.route('/api/chat/end/<dialog_id>', methods=['POST'])
|
| def end_conversation(dialog_id):
|
| """End a conversation"""
|
| if dialog_id in active_dialogs:
|
| del active_dialogs[dialog_id]
|
| return jsonify({
|
| 'success': True,
|
| 'dialog_id': dialog_id,
|
| 'message': 'Conversation ended'
|
| })
|
| else:
|
| return jsonify({'error': 'dialog_id not found'}), 404
|
|
|
|
|
|
|
|
|
|
|
|
|
| @app.route('/')
|
| def index():
|
| return render_template('chat.html')
|
|
|
|
|
| @app.route('/chat')
|
| def chat_page():
|
| """Simple chat interface"""
|
| return '''
|
| <!DOCTYPE html>
|
| <html>
|
| <head>
|
| <title>NoahsKI - Smart Conversation</title>
|
| <style>
|
| body { font-family: Arial; max-width: 800px; margin: 50px auto; }
|
| #chat { border: 1px solid #ccc; height: 400px; overflow-y: auto; padding: 10px; margin-bottom: 10px; }
|
| .message { margin: 10px 0; padding: 10px; border-radius: 5px; }
|
| .user { background: #007bff; color: white; }
|
| .ai { background: #e9ecef; }
|
| input { width: 100%; padding: 10px; }
|
| button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; }
|
| </style>
|
| </head>
|
| <body>
|
| <h1>NoahsKI - Smart Conversation System</h1>
|
| <div id="chat"></div>
|
| <input type="text" id="message" placeholder="Deine Nachricht..." />
|
| <button onclick="sendMessage()">Send</button>
|
|
|
| <script>
|
| let dialogId = null;
|
|
|
| async function sendMessage() {
|
| const msg = document.getElementById('message').value;
|
| if (!msg) return;
|
|
|
| // Display user message
|
| addMessage('user', msg);
|
| document.getElementById('message').value = '';
|
|
|
| try {
|
| let response;
|
|
|
| if (!dialogId) {
|
| // Start new conversation
|
| response = await fetch('/api/chat/new', {
|
| method: 'POST',
|
| headers: {'Content-Type': 'application/json'},
|
| body: JSON.stringify({
|
| user_id: 'web_user',
|
| message: msg
|
| })
|
| });
|
| } else {
|
| // Continue conversation
|
| response = await fetch('/api/chat/continue', {
|
| method: 'POST',
|
| headers: {'Content-Type': 'application/json'},
|
| body: JSON.stringify({
|
| dialog_id: dialogId,
|
| message: msg
|
| })
|
| });
|
| }
|
|
|
| const data = await response.json();
|
|
|
| if (!dialogId) {
|
| dialogId = data.dialog_id;
|
| }
|
|
|
| addMessage('ai', data.response);
|
|
|
| } catch (error) {
|
| addMessage('ai', 'Error: ' + error.message);
|
| }
|
| }
|
|
|
| function addMessage(sender, text) {
|
| const chat = document.getElementById('chat');
|
| const div = document.createElement('div');
|
| div.className = 'message ' + sender;
|
| div.textContent = text;
|
| chat.appendChild(div);
|
| chat.scrollTop = chat.scrollHeight;
|
| }
|
|
|
| // Allow Enter key
|
| document.getElementById('message').addEventListener('keypress', (e) => {
|
| if (e.key === 'Enter') sendMessage();
|
| });
|
| </script>
|
| </body>
|
| </html>
|
| '''
|
|
|
|
|
|
|
|
|
|
|
|
|
| if __name__ == '__main__':
|
| print("""
|
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| β β
|
| β NoahsKI - Smart Conversation System β
|
| β β Multi-turn Dialog Management β
|
| β β Intent Recognition β
|
| β β Realistic Training Data β
|
| β β Natural Conversations β
|
| β β
|
| β Visit: http://localhost:5000/chat β
|
| β β
|
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| """)
|
|
|
| app.run(debug=True, port=5000)
|
|
|