File size: 11,105 Bytes
42e8047
c19d193
42e8047
6aae614
9b5b26a
 
0aa7981
42e8047
29bd583
42e8047
9b5b26a
42e8047
7a0dcb9
42e8047
9b5b26a
42e8047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a0dcb9
 
42e8047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19d079f
42e8047
0aa7981
ae7a494
e121372
0aa7981
 
 
13d500a
8c01ffb
42e8047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
8fe992b
42e8047
 
29bd583
 
8fe992b
 
42e8047
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
from smolagents import CodeAgent, HfApiModel, tool
import yaml
import random
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

@tool
def generate_famous_quote(topic: str) -> str:
    """
    Generates a famous quote related to the provided topic.
    Args:
        topic (str): The topic or theme for the quote.
    Returns:
        str: A famous quote related to the topic and its author.
    """
    # Dictionary of quotes by topic
    quotes_by_topic = {
        "love": [
            "The greatest happiness of life is the conviction that we are loved; loved for ourselves, or rather, loved in spite of ourselves. — Victor Hugo",
            "Love is composed of a single soul inhabiting two bodies. — Aristotle",
            "Being deeply loved by someone gives you strength, while loving someone deeply gives you courage. — Lao Tzu",
            "Where there is love, there is life. — Mahatma Gandhi",
            "The best thing to hold onto in life is each other. — Audrey Hepburn"
        ],
        "wisdom": [
            "The only true wisdom is in knowing you know nothing. — Socrates",
            "Wisdom is not a product of schooling but of the lifelong attempt to acquire it. — Albert Einstein",
            "The fool doth think he is wise, but the wise man knows himself to be a fool. — William Shakespeare",
            "By three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest. — Confucius",
            "The beginning of wisdom is the definition of terms. — Socrates"
        ],
        "success": [
            "Success is not final, failure is not fatal: It is the courage to continue that counts. — Winston Churchill",
            "The way to get started is to quit talking and begin doing. — Walt Disney",
            "Don't be distracted by criticism. Remember, the only taste of success some people get is to take a bite out of you. — Zig Ziglar",
            "Success usually comes to those who are too busy to be looking for it. — Henry David Thoreau",
            "I never dreamed about success, I worked for it. — Estée Lauder"
        ],
        "happiness": [
            "Happiness is not something ready-made. It comes from your own actions. — Dalai Lama",
            "The happiness of your life depends upon the quality of your thoughts. — Marcus Aurelius",
            "The most important thing is to enjoy your life—to be happy—it's all that matters. — Audrey Hepburn",
            "Happiness is when what you think, what you say, and what you do are in harmony. — Mahatma Gandhi",
            "Count your age by friends, not years. Count your life by smiles, not tears. — John Lennon"
        ],
        "time": [
            "The two most powerful warriors are patience and time. — Leo Tolstoy",
            "Time is what we want most, but what we use worst. — William Penn",
            "Yesterday is gone. Tomorrow has not yet come. We have only today. Let us begin. — Mother Teresa",
            "Time you enjoy wasting is not wasted time. — Marthe Troly-Curtin",
            "The future starts today, not tomorrow. — Pope John Paul II"
        ],
        "friendship": [
            "A real friend is one who walks in when the rest of the world walks out. — Walter Winchell",
            "Friendship is born at that moment when one person says to another, 'What! You too? I thought I was the only one.' — C.S. Lewis",
            "A friend is someone who knows all about you and still loves you. — Elbert Hubbard",
            "A single rose can be my garden... a single friend, my world. — Leo Buscaglia",
            "Friendship is the only cement that will ever hold the world together. — Woodrow Wilson"
        ],
        "courage": [
            "Courage is resistance to fear, mastery of fear, not absence of fear. — Mark Twain",
            "It takes courage to grow up and become who you really are. — E.E. Cummings",
            "Success is not final, failure is not fatal: It is the courage to continue that counts. — Winston Churchill",
            "Courage is found in unlikely places. — J.R.R. Tolkien",
            "You cannot swim for new horizons until you have courage to lose sight of the shore. — William Faulkner"
        ],
        "change": [
            "The only way to make sense out of change is to plunge into it, move with it, and join the dance. — Alan Watts",
            "Change is the law of life. And those who look only to the past or present are certain to miss the future. — John F. Kennedy",
            "Everyone thinks of changing the world, but no one thinks of changing himself. — Leo Tolstoy",
            "Be the change that you wish to see in the world. — Mahatma Gandhi",
            "Those who cannot change their minds cannot change anything. — George Bernard Shaw"
        ],
        "education": [
            "Education is the most powerful weapon which you can use to change the world. — Nelson Mandela",
            "The function of education is to teach one to think intensively and to think critically. — Martin Luther King, Jr.",
            "Education is not the filling of a pail, but the lighting of a fire. — W.B. Yeats",
            "The roots of education are bitter, but the fruit is sweet. — Aristotle",
            "An investment in knowledge pays the best interest. — Benjamin Franklin"
        ],
        "faith": [
            "Faith is taking the first step even when you don't see the whole staircase. — Martin Luther King, Jr.",
            "Faith consists in believing when it is beyond the power of reason to believe. — Voltaire",
            "Keep your faith in all beautiful things; in the sun when it is hidden, in the Spring when it is gone. — Roy R. Gilson",
            "Faith is the bird that feels the light when the dawn is still dark. — Rabindranath Tagore",
            "Faith is to believe what you do not see; the reward of this faith is to see what you believe. — Saint Augustine"
        ],
        "hope": [
            "Hope is being able to see that there is light despite all of the darkness. — Desmond Tutu",
            "We must accept finite disappointment, but never lose infinite hope. — Martin Luther King, Jr.",
            "Hope is the thing with feathers that perches in the soul. — Emily Dickinson",
            "Where there is no vision, there is no hope. — George Washington Carver",
            "A leader is a dealer in hope. — Napoleon Bonaparte"
        ],
        "perseverance": [
            "It does not matter how slowly you go as long as you do not stop. — Confucius",
            "Perseverance is not a long race; it is many short races one after the other. — Walter Elliot",
            "Many of life's failures are people who did not realize how close they were to success when they gave up. — Thomas Edison",
            "Through perseverance many people win success out of what seemed destined to be certain failure. — Benjamin Disraeli",
            "The difference between a successful person and others is not a lack of strength, not a lack of knowledge, but rather a lack in will. — Vince Lombardi"
        ]
    }
    
    # Normalize the topic (convert to lowercase)
    topic_lower = topic.lower()
    
    # Find the closest matching topic
    if topic_lower in quotes_by_topic:
        # Topic directly matches
        relevant_quotes = quotes_by_topic[topic_lower]
    else:
        # Search for partial matches in topic keywords
        matched_topics = []
        for key in quotes_by_topic:
            if key in topic_lower or topic_lower in key:
                matched_topics.append(key)
        
        if matched_topics:
            # Use quotes from the first matching topic
            relevant_quotes = quotes_by_topic[matched_topics[0]]
        else:
            # No match found - use a generic response
            return f"No famous quotes found for '{topic}'. Try topics like: love, wisdom, success, happiness, time, friendship, courage, change, education, faith, hope, or perseverance."
    
    # Return a random quote from the relevant ones
    return random.choice(relevant_quotes)

# Setup agent
final_answer = FinalAnswerTool()

model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct'
)

# Custom prompt templates for the quote generator agent
quote_prompt_templates = {
    "react-system": """You are a helpful agent that provides famous quotes on various topics.
You have access to the following tools:

{tools_string}

When a user enters a topic, use the generate_famous_quote tool to find a relevant quote on that topic.
Return the quote to the user using the final_answer tool.

To use a tool, output an action in this format:
```py
action = tool_name(arg1=value1, arg2=value2, ...)
```

Always use Python syntax for calling tools. After using a tool, analyze the result to determine what to do next. Use final_answer to return your answer when complete.
""",
    "react-human": "{input_string}",
    "react-assistant": "{agent_response}",
}

# Load prompts.yaml if it exists, otherwise use our custom templates
try:
    with open("prompts.yaml", 'r') as stream:
        prompt_templates = yaml.safe_load(stream)
        prompt_templates.update(quote_prompt_templates)
except:
    prompt_templates = quote_prompt_templates

# Create the agent
agent = CodeAgent(
    model=model,
    tools=[final_answer, generate_famous_quote],
    max_steps=3,  # Reduced steps since this is a simple task
    verbosity_level=1,
    prompt_templates=prompt_templates
)

# Create a custom Gradio UI
class QuoteGeneratorUI(GradioUI):
    def launch(self, **kwargs):
        import gradio as gr
        
        with gr.Blocks(theme=gr.themes.Soft()) as demo:
            gr.Markdown("# Famous Quotes Generator")
            gr.Markdown("Enter a topic to receive a famous quote related to it.")
            
            with gr.Row():
                with gr.Column():
                    topic_input = gr.Textbox(label="Enter a topic (e.g., love, wisdom, success)")
                    submit_btn = gr.Button("Get Quote", variant="primary")
            
            with gr.Row():
                with gr.Column():
                    quote_output = gr.Markdown(label="Your Quote")
            
            def get_quote(topic):
                if not topic or topic.strip() == "":
                    return "Please enter a topic to receive a quote."
                
                try:
                    quote = generate_famous_quote(topic)
                    return f"### Quote on '{topic}':\n\n> {quote}"
                except Exception as e:
                    return f"Error generating quote: {str(e)}"
            
            submit_btn.click(get_quote, inputs=topic_input, outputs=quote_output)
        
        demo.launch(**kwargs)

# Launch the custom UI
QuoteGeneratorUI(agent).launch()