desiree commited on
Commit
28fff71
·
verified ·
1 Parent(s): e44659b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -93
app.py CHANGED
@@ -1,11 +1,15 @@
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import json
4
  import re
 
5
 
6
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
7
-
8
- SYSTEM_PROMPT = """You are an AI agent planner that helps break down tasks into clear, actionable steps. For each task, you will:
 
 
9
  1. Analyze the task and break it down into specific sub-tasks
10
  2. Create a structured plan with numbered steps
11
  3. Include any relevant considerations or potential challenges
@@ -26,103 +30,125 @@ SYSTEM_PROMPT = """You are an AI agent planner that helps break down tasks into
26
 
27
  Keep your responses focused and practical."""
28
 
29
- def parse_json_response(response_text):
30
- """Extract JSON from the response text."""
31
- try:
32
- # Find JSON pattern in the text
33
- json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
34
- if json_match:
35
- json_str = json_match.group()
36
- return json.loads(json_str)
37
- return None
38
- except json.JSONDecodeError:
39
- return None
40
 
41
- def format_plan(plan_json):
42
- """Format the JSON plan into a readable markdown string."""
43
- if not plan_json:
44
- return "Error: Could not parse the plan. Please try again."
45
-
46
- output = []
47
- output.append("# Task Analysis")
48
- output.append(plan_json.get("task_analysis", ""))
49
- output.append("\n## Detailed Steps")
50
-
51
- for step in plan_json.get("steps", []):
52
- output.append(f"\n### Step {step.get('step_number')}: {step.get('description')}")
53
- output.append(f"- Estimated time: {step.get('estimated_time')}")
54
- if step.get('considerations'):
55
- output.append("\nConsiderations:")
56
- for consideration in step['considerations']:
57
- output.append(f"- {consideration}")
58
-
59
- if plan_json.get("potential_challenges"):
60
- output.append("\n## Potential Challenges")
61
- for challenge in plan_json["potential_challenges"]:
62
- output.append(f"- {challenge}")
63
-
64
- if plan_json.get("resources_needed"):
65
- output.append("\n## Required Resources")
66
- for resource in plan_json["resources_needed"]:
67
- output.append(f"- {resource}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- return "\n".join(output)
 
 
70
 
71
- def respond(
72
- message,
73
- history: list[tuple[str, str]],
74
- system_message=SYSTEM_PROMPT,
75
- max_tokens=1024,
76
- temperature=0.7,
77
- top_p=0.95,
78
- ):
79
- messages = [{"role": "system", "content": system_message}]
80
 
81
- for user_msg, assistant_msg in history:
82
- if user_msg:
83
- messages.append({"role": "user", "content": user_msg})
84
- if assistant_msg:
85
- messages.append({"role": "assistant", "content": assistant_msg})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- messages.append({"role": "user", "content": message})
88
 
89
- response = ""
90
- for message in client.chat_completion(
91
- messages,
92
- max_tokens=max_tokens,
93
- stream=True,
94
- temperature=temperature,
95
- top_p=top_p,
96
- ):
97
- token = message.choices[0].delta.content
98
- response += token
99
-
100
- # Try to parse and format JSON as it comes in
101
- plan_json = parse_json_response(response)
102
- if plan_json:
103
- formatted_response = format_plan(plan_json)
104
- yield formatted_response
105
- else:
106
- yield response
107
 
108
- demo = gr.ChatInterface(
109
- respond,
110
- additional_inputs=[
111
- gr.Textbox(value=SYSTEM_PROMPT, label="System message", lines=5),
112
- gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Max new tokens"),
113
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
114
- gr.Slider(
115
- minimum=0.1,
116
- maximum=1.0,
117
- value=0.95,
118
- step=0.05,
119
- label="Top-p (nucleus sampling)",
120
- ),
121
- ],
122
- title="AI Agent Planner",
123
- description="I help break down tasks into clear, actionable steps. Describe your task, and I'll create a detailed plan.",
124
- theme=gr.themes.Soft(),
125
- )
126
 
127
  if __name__ == "__main__":
 
128
  demo.launch()
 
1
+ import concurrent.futures
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
  import json
5
  import re
6
+ import traceback
7
 
8
+ class AgentPlanner:
9
+ def __init__(self):
10
+ self.client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
11
+ self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
12
+ self.system_prompt = """You are an AI agent planner that helps break down tasks into clear, actionable steps. For each task, you will:
13
  1. Analyze the task and break it down into specific sub-tasks
14
  2. Create a structured plan with numbered steps
15
  3. Include any relevant considerations or potential challenges
 
30
 
31
  Keep your responses focused and practical."""
32
 
33
+ def parse_json_response(self, response_text):
34
+ """Extract JSON from the response text."""
35
+ try:
36
+ json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
37
+ if json_match:
38
+ json_str = json_match.group()
39
+ return json.loads(json_str)
40
+ return None
41
+ except json.JSONDecodeError:
42
+ return None
 
43
 
44
+ def format_plan(self, plan_json):
45
+ """Format the JSON plan into a readable markdown string."""
46
+ if not plan_json:
47
+ return "Error: Could not parse the plan. Please try again."
48
+
49
+ output = []
50
+ output.append("# Task Analysis")
51
+ output.append(plan_json.get("task_analysis", ""))
52
+ output.append("\n## Detailed Steps")
53
+
54
+ for step in plan_json.get("steps", []):
55
+ output.append(f"\n### Step {step.get('step_number')}: {step.get('description')}")
56
+ output.append(f"- Estimated time: {step.get('estimated_time')}")
57
+ if step.get('considerations'):
58
+ output.append("\nConsiderations:")
59
+ for consideration in step['considerations']:
60
+ output.append(f"- {consideration}")
61
+
62
+ if plan_json.get("potential_challenges"):
63
+ output.append("\n## Potential Challenges")
64
+ for challenge in plan_json["potential_challenges"]:
65
+ output.append(f"- {challenge}")
66
+
67
+ if plan_json.get("resources_needed"):
68
+ output.append("\n## Required Resources")
69
+ for resource in plan_json["resources_needed"]:
70
+ output.append(f"- {resource}")
71
+
72
+ return "\n".join(output)
73
+
74
+ def generate_plan(self, task, max_tokens=1024, temperature=0.7, top_p=0.95):
75
+ try:
76
+ messages = [
77
+ {"role": "system", "content": self.system_prompt},
78
+ {"role": "user", "content": task}
79
+ ]
80
+
81
+ response = ""
82
+ for message in self.client.chat_completion(
83
+ messages,
84
+ max_tokens=max_tokens,
85
+ stream=True,
86
+ temperature=temperature,
87
+ top_p=top_p,
88
+ ):
89
+ token = message.choices[0].delta.content
90
+ response += token
91
+
92
+ # Try to parse and format JSON as it comes in
93
+ plan_json = self.parse_json_response(response)
94
+ if plan_json:
95
+ formatted_response = self.format_plan(plan_json)
96
+ yield formatted_response
97
+ else:
98
+ yield response
99
+ except Exception as e:
100
+ yield f"Error generating plan: {str(e)}\n{traceback.format_exc()}"
101
+
102
+ def __del__(self):
103
+ self.executor.shutdown(wait=False)
104
+
105
+ def create_interface():
106
+ planner = AgentPlanner()
107
 
108
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
109
+ gr.Markdown("# AI Agent Planner")
110
+ gr.Markdown("Get organized, structured plans for any task")
111
 
112
+ task_input = gr.Textbox(
113
+ label="Task Description",
114
+ placeholder="Describe the task you need help planning...",
115
+ lines=3
116
+ )
 
 
 
 
117
 
118
+ with gr.Row():
119
+ max_tokens = gr.Slider(
120
+ minimum=1,
121
+ maximum=2048,
122
+ value=1024,
123
+ step=1,
124
+ label="Max Tokens"
125
+ )
126
+ temperature = gr.Slider(
127
+ minimum=0.1,
128
+ maximum=4.0,
129
+ value=0.7,
130
+ step=0.1,
131
+ label="Temperature"
132
+ )
133
+ top_p = gr.Slider(
134
+ minimum=0.1,
135
+ maximum=1.0,
136
+ value=0.95,
137
+ step=0.05,
138
+ label="Top-p"
139
+ )
140
 
141
+ output = gr.Markdown(label="Generated Plan")
142
 
143
+ generate_btn = gr.Button("Generate Plan", variant="primary")
144
+ generate_btn.click(
145
+ planner.generate_plan,
146
+ inputs=[task_input, max_tokens, temperature, top_p],
147
+ outputs=output
148
+ )
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
+ return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
  if __name__ == "__main__":
153
+ demo = create_interface()
154
  demo.launch()