File size: 2,358 Bytes
29d384c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# app.py

from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
from tools.final_answer import FinalAnswerTool
import datetime
import pytz
import yaml
import gradio as gr

# ✅✅✅ ---- Natural language time tool ----
@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """
    A tool that fetches the current local time in a specified timezone.
    Args:
        timezone: A string representing a valid timezone (e.g., 'Europe/London').
    """
    try:
        tz = pytz.timezone(timezone)
        local_time = datetime.datetime.now(tz).strftime("%A, %B %d, %Y %I:%M %p")
        return f"The current local time in {timezone} is {local_time}."
    except Exception as e:
        return f"Sorry, I couldn’t find the time for {timezone}: {str(e)}"

# ✅✅✅ ---- Final Answer Tool ----
final_answer = FinalAnswerTool()

# ✅✅✅ ---- Hugging Face Model ----
model = HfApiModel(
    max_tokens=2048,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
)

# ✅✅✅ ---- Load optional tool from Hub ----
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)

# ✅✅✅ ---- System prompt template ----
# This will ensure the agent keeps full sentences!
prompt_templates = {
    "system": """You are a helpful agent that thinks step by step.
You must always return your final answer as a clear, complete sentence in natural language.
If you call tools, use their output exactly and do not strip details.
When you have the final information, pass it using the FinalAnswerTool.
"""
}

# ✅✅✅ ---- Build the CodeAgent ----
agent = CodeAgent(
    model=model,
    tools=[
        get_current_time_in_timezone,
        DuckDuckGoSearchTool(),
        image_generation_tool,
        final_answer
    ],
    max_steps=6,
    verbosity_level=1,
    prompt_templates=prompt_templates
)

# ✅✅✅ ---- Gradio UI ----
def agentic_chat(user_input):
    result = agent.run(user_input)
    if hasattr(result, 'final_answer'):
        return result.final_answer
    else:
        return str(result)

iface = gr.Interface(
    fn=agentic_chat,
    inputs="text",
    outputs="text",
    title="Agentic AI Example",
    description="Ask me anything! I will reason step-by-step and provide clear final answers."
)

if __name__ == "__main__":
    iface.launch()