File size: 3,535 Bytes
e947927
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import asyncio
import os
from agents import Agent, Runner
from agents.extensions.memory import RedisSession
import dotenv
import redis.asyncio as aioredis

dotenv.load_dotenv()
Redis_url = os.getenv("REDIS_URL")


#===============transformers================
from transformers import pipeline
import re
from datetime import datetime
import json
import requests

# Initialize summarization model
try:
    print("πŸš€ Loading BART model for summarization...")
    summarizer = pipeline("summarization", model="facebook/bart-large-cnn", tokenizer="facebook/bart-large-cnn",framework="pt")
except Exception as e:
    print(f"Error loading BART model: {e}")
    summarizer = None

print("βœ… Summarization pipeline ready!")




# ---------- Utility Functions ----------

async def get_sessions(user_login_id: str):
    """
    Get all session IDs for a given user (based on key prefix).
    """
    redis = await aioredis.from_url(Redis_url)
    pattern = f"{user_login_id}:*"
    keys = await redis.keys(pattern)
    sessions = [key.decode().replace(f"{user_login_id}:", "") for key in keys]
    await redis.close()
    return sessions


async def get_session_history(user_login_id: str, session_id: str):
    """
    Retrieve chat history for a given user's session.
    """
    try:
        session = RedisSession.from_url(
            session_id,
            url=Redis_url,
            key_prefix=f"{user_login_id}:",
        )
        if not await session.ping():
            raise Exception("Redis connection failed")

        items = await session.get_items()
        history = [
            {"role": msg.get("role", "unknown"), "content": msg.get("content", "")}
            for msg in items
        ]
        await session.close()
        return history

    except Exception as e:
        return {"error": str(e)}


async def delete_session(user_login_id: str, session_id: str):
    """
    Delete a specific session for a given user.
    """
    try:
        session = RedisSession.from_url(
            session_id,
            url=Redis_url,
            key_prefix=f"{user_login_id}:",
        )
        if not await session.ping():
            raise Exception("Redis connection failed")

        await session.clear_session()
        await session.close()
        return {"status": "success", "message": f"Session {session_id} deleted"}

    except Exception as e:
        return {"status": "error", "message": str(e)}


# ---------- Example Usage ----------

async def main_demo():
    user_id = "vatsav_user2"
    session_id = ":uuid_12345"

    print("Creating session...")
    session = RedisSession.from_url(
        session_id,
        url=Redis_url,
        key_prefix=f"{user_id}:",
    )

    agent = Agent(name="Assistant", instructions="Be concise.")
    await Runner.run(agent, "Hello!", session=session)
    await Runner.run(agent, "How are you?", session=session)
    await session.close()

    print("\n--- All Sessions ---")
    print(await get_sessions(user_id))
    print("lenth of the sessions: ", len(await get_sessions(user_id)) or 0)

    print("\n--- Session History ---")
    
    history = await get_session_history(user_id, session_id)
    print("lenght of the history: ", len(history) or 0)
    print(history)
    print("\nHistoryends=======================:")
    for msg in history:
        print(f"{msg['role']}: {msg['content']}")
       


    

    print("\n--- Delete Session ---")
    print(await delete_session(user_id, session_id))


if __name__ == "__main__":
    asyncio.run(main_demo())