File size: 3,351 Bytes
b1e93de
 
 
 
 
 
f255c65
b1e93de
 
 
f255c65
 
 
 
 
 
 
 
 
 
 
 
 
b1e93de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f255c65
b1e93de
 
 
 
 
 
 
 
f255c65
 
 
 
 
 
 
 
b1e93de
f255c65
 
 
 
 
 
 
b1e93de
 
f255c65
 
 
 
 
 
 
b1e93de
f255c65
 
b1e93de
 
 
 
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
import os
import time
import gradio as gr
from groq import Groq
import re

# Initialize Groq
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
MODEL = "llama-3.3-70b-versatile"

# ------------------ Direct Answer ------------------
def answer_anything(question):
    response = client.chat.completions.create(
        model=MODEL,
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": question}
        ],
        temperature=0.5
    )
    return response.choices[0].message.content

# ------------------ Autonomous Agent ------------------
class AutonomousAgent:
    def __init__(self, goal):
        self.goal = goal
        self.memory = []
        self.completed_tasks = []

    def think(self, prompt):
        response = client.chat.completions.create(
            model=MODEL,
            messages=[
                {"role": "system", "content": "You are an autonomous AI agent that works without human intervention."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.5,
        )
        return response.choices[0].message.content

    def plan_tasks(self):
        prompt = f"""
        Goal: {self.goal}
        Create a step-by-step task plan to achieve this goal.
        Use short, clear tasks.
        """
        return self.think(prompt)

    def execute_task(self, task):
        memory_context = "\n".join([f"Task: {m['task']} Result: {m['result']}" for m in self.memory])
        prompt = f"""
        Based on memory:
        {memory_context}

        Execute this task fully:
        {task}

        Output the result clearly.
        """
        return self.think(prompt)

    def run(self, max_steps=6, show_steps=False):
        tasks_text = self.plan_tasks()
        tasks = [re.sub(r'^\d+\.\s*', '', t).strip() for t in tasks_text.split("\n") if t.strip()]

        results = []
        for i, task in enumerate(tasks[:max_steps], 1):
            result = self.execute_task(task)
            self.memory.append({"task": task, "result": result})
            self.completed_tasks.append(task)
            if show_steps:
                results.append(f"STEP {i}: {task}\nRESULT: {result}\n{'-'*40}")

        # Return either detailed steps or just the final result
        if show_steps:
            return "\n".join(results)
        else:
            return result  # last task result only

# ------------------ Gradio Interface ------------------
def run(user_input, mode, max_steps, show_steps):
    if mode == "Direct Answer":
        return answer_anything(user_input)
    elif mode == "Autonomous Agent":
        agent = AutonomousAgent(user_input)
        return agent.run(max_steps=max_steps, show_steps=show_steps)

interface = gr.Interface(
    fn=run,
    inputs=[
        gr.Textbox(label="Enter your question or goal"),
        gr.Radio(choices=["Direct Answer", "Autonomous Agent"], label="Mode"),
        gr.Slider(1, 10, value=6, step=1, label="Max Steps (for Autonomous Agent)"),
        gr.Checkbox(label="Show steps (for Autonomous Agent)", value=True)
    ],
    outputs="text",
    title="🤖 Combined AI Agent",
    description="Choose 'Direct Answer' for quick responses, or 'Autonomous Agent' for multi-step goal execution."
)

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