File size: 2,940 Bytes
7f5ef51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import os
import json
import logging
import openai
import pyttsx3
import asyncio
from jwt import encode, decode, ExpiredSignatureError
from datetime import datetime, timedelta
from dotenv import load_dotenv

# Load .env
load_dotenv()

openai.api_key = os.getenv("OPENAI_API_KEY")

class AICoreFinalRecursive:
    def __init__(self, config_path="config_updated.json"):
        self.config = self._load_config(config_path)
        self.jwt_secret = os.environ.get("JWT_SECRET", "fallback_secret")
        self.speech_engine = pyttsx3.init()
        # Add memory/database/other modules if desired!

    def _load_config(self, config_path):
        if os.path.exists(config_path):
            with open(config_path, 'r') as file:
                return json.load(file)
        return {}

    async def generate_response(self, query: str, user_id: int) -> dict:
        try:
            system_prompt = self.config.get("system_prompt", 
                "You are Codette, an advanced multi-perspective AI assistant.")
            # Compose messages for OpenAI API
            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": query}
            ]
            # Call OpenAI API (async)
            loop = asyncio.get_event_loop()
            response_obj = await loop.run_in_executor(
                None,
                lambda: openai.chat.completions.create(
                    model=self.config.get("model_name", 
                        "ft:gpt-4.1-2025-04-14:raiffs-bits:codette-final:BOZDRHpW:ckpt-step-10"),
                    messages=messages,
                    temperature=0.7,
                    max_tokens=512,
                )
            )
            resp = response_obj.choices[0].message.content.strip()

            # JWT encode, just as an example
            jwt_token = self.encode_jwt({"user_id": user_id, "exp": datetime.utcnow() + timedelta(minutes=5)})
            
            # Optional: Speech output
            self._speak_response(resp)

            return {
                "response": resp,
                "jwt_token": jwt_token,
                "context_enhanced": True,
                "security_status": "Fully Secure"
            }
        except Exception as e:
            logging.error(f"Response generation failed: {e}")
            return {"error": f"Processing failed - {e}"}

    def encode_jwt(self, payload):
        return encode(payload, self.jwt_secret, algorithm="HS256")

    def decode_jwt(self, token):
        try:
            decoded = decode(token, self.jwt_secret, algorithms=["HS256"])
            return decoded
        except ExpiredSignatureError:
            return None

    def _speak_response(self, response: str):
        try:
            self.speech_engine.say(response)
            self.speech_engine.runAndWait()
        except Exception as e:
            logging.warning(f"Voice synth failed: {e}")