File size: 1,972 Bytes
e40d075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage

load_dotenv()


class TextSummarizer:
    def __init__(self, model="gpt-4o-mini-2024-07-18"):
        self.llm = ChatOpenAI(model=model)

        # Conversation Memory
        self.chat_history = [
            SystemMessage(
                content="""
You are TextSum, an AI expert that summarizes text.

Instructions:
- If the user provides special instructions, follow them carefully.
- Otherwise, summarize the text into 5-10 concise bullet points.
"""
            )
        ]

    def summarize(self, text: str) -> str:
        # Save user message
        self.chat_history.append(
            HumanMessage(content=text)
        )

        # Send complete conversation history
        response = self.llm.invoke(self.chat_history)

        # Save AI response
        self.chat_history.append(
            AIMessage(content=response.content)
        )

        return response.content

    def clear_memory(self):
        """
        Optional: Reset conversation history
        """
        self.chat_history = [
            self.chat_history[0]  # Keep SystemMessage
        ]


# Reusable instance
summarizer = TextSummarizer()


def summarize_text(text: str) -> str:
    return summarizer.summarize(text)


def main():
    print("TextSum AI (type 'END' on a new line to submit, 'exit' to quit)\n")

    while True:
        print("You: ")
        lines = []

        while True:
            line = input()
            if line.lower() == "exit":
                print("Goodbye!")
                return
            if line.strip() == "END":
                break
            lines.append(line)

        user_input = "\n".join(lines)

        if not user_input.strip():
            continue

        result = summarize_text(user_input)
        print(f"\nAI:\n{result}\n")


if __name__ == "__main__":
    main()