levisstrauss commited on
Commit
a87ed52
·
1 Parent(s): 7d69d21

Fix API error

Browse files
Files changed (3) hide show
  1. app.py +9 -1
  2. base_agents.py +260 -335
  3. requirements.txt +1 -4
app.py CHANGED
@@ -950,7 +950,15 @@ def create_interface():
950
  """Validate the API key format."""
951
  if not api_key or len(api_key) < 20:
952
  return "❌ Please enter a valid API key"
953
- return "✅ API key accepted"
 
 
 
 
 
 
 
 
954
 
955
  def load_example(example_name: str) -> str:
956
  """Load an example product specification."""
 
950
  """Validate the API key format."""
951
  if not api_key or len(api_key) < 20:
952
  return "❌ Please enter a valid API key"
953
+
954
+ if api_key.startswith("sk-ant-"):
955
+ return "✅ Anthropic Claude key detected"
956
+ elif api_key.startswith("voc-"):
957
+ return "✅ Vocareum key detected (requires Vocareum network)"
958
+ elif api_key.startswith("sk-"):
959
+ return "✅ OpenAI key detected"
960
+ else:
961
+ return "⚠️ Unknown key format - will try OpenAI"
962
 
963
  def load_example(example_name: str) -> str:
964
  """Load an example product specification."""
base_agents.py CHANGED
@@ -1,68 +1,195 @@
1
  """
2
  Base Agents Library for AI Project Planner
3
 
4
- A collection of reusable AI agents for building agentic workflows.
5
- Optimized for web deployment with proper error handling and logging.
 
 
 
 
 
6
  """
7
 
8
  from openai import OpenAI
9
  import numpy as np
10
  from typing import Dict, Any, List, Optional, Callable
11
  import logging
 
12
 
13
  # Configure logging
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
 
 
 
17
 
18
- class DirectPromptAgent:
 
 
 
 
 
 
19
  """
20
- A Direct Prompt Agent that relays user input directly to the LLM
21
- without additional context, memory, or specialized tools.
22
-
23
- This is the most straightforward method for interacting with an LLM.
24
  """
25
-
26
- def __init__(self, openai_api_key: str, base_url: str = None):
27
- """
28
- Initialize the DirectPromptAgent.
29
-
30
- Args:
31
- openai_api_key: The OpenAI API key for authentication.
32
- base_url: Optional custom base URL for API calls.
33
- """
34
- self.openai_api_key = openai_api_key
35
  self.base_url = base_url
36
-
37
- def _get_client(self) -> OpenAI:
38
- """Create and return an OpenAI client instance."""
39
- if self.base_url:
40
- return OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
41
- return OpenAI(api_key=self.openai_api_key)
42
 
43
- def respond(self, prompt: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  """
45
- Generate a response by passing the user prompt directly to the LLM.
46
-
47
  Args:
48
- prompt: The user's input prompt.
49
-
 
 
50
  Returns:
51
- The textual content of the LLM's response.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  try:
54
- client = self._get_client()
55
-
56
- response = client.chat.completions.create(
57
- model="gpt-3.5-turbo",
58
- messages=[
59
- {"role": "user", "content": prompt}
60
- ],
61
- temperature=0
62
- )
63
-
64
- return response.choices[0].message.content
65
-
66
  except Exception as e:
67
  logger.error(f"DirectPromptAgent error: {str(e)}")
68
  raise
@@ -71,56 +198,22 @@ class DirectPromptAgent:
71
  class AugmentedPromptAgent:
72
  """
73
  An Augmented Prompt Agent that responds according to a predefined persona.
74
-
75
- This agent explicitly adopts a persona via a system prompt, leading to
76
- more targeted and contextually relevant outputs.
77
  """
78
-
79
  def __init__(self, openai_api_key: str, persona: str, base_url: str = None):
80
- """
81
- Initialize the AugmentedPromptAgent.
82
-
83
- Args:
84
- openai_api_key: The OpenAI API key for authentication.
85
- persona: The persona the agent should assume.
86
- base_url: Optional custom base URL for API calls.
87
- """
88
- self.openai_api_key = openai_api_key
89
  self.persona = persona
90
- self.base_url = base_url
91
-
92
- def _get_client(self) -> OpenAI:
93
- """Create and return an OpenAI client instance."""
94
- if self.base_url:
95
- return OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
96
- return OpenAI(api_key=self.openai_api_key)
97
 
98
  def respond(self, input_text: str) -> str:
99
- """
100
- Generate a response using the defined persona.
101
-
102
- Args:
103
- input_text: The user's input prompt.
104
-
105
- Returns:
106
- The textual content of the LLM's response.
107
- """
108
  try:
109
- client = self._get_client()
110
-
111
  system_prompt = f"{self.persona} Forget all previous conversational context."
112
-
113
- response = client.chat.completions.create(
114
- model="gpt-3.5-turbo",
115
- messages=[
116
- {"role": "system", "content": system_prompt},
117
- {"role": "user", "content": input_text}
118
- ],
119
- temperature=1.0
120
- )
121
-
122
- return response.choices[0].message.content
123
-
124
  except Exception as e:
125
  logger.error(f"AugmentedPromptAgent error: {str(e)}")
126
  raise
@@ -128,70 +221,34 @@ class AugmentedPromptAgent:
128
 
129
  class KnowledgeAugmentedPromptAgent:
130
  """
131
- A Knowledge Augmented Prompt Agent that incorporates specific knowledge
132
- alongside a defined persona when responding to prompts.
133
-
134
- This agent ensures answers are based on explicitly provided information
135
- rather than the LLM's inherent knowledge.
136
  """
137
-
138
  def __init__(
139
- self,
140
- openai_api_key: str,
141
- persona: str,
142
- knowledge: str,
143
- base_url: str = None
144
  ):
145
- """
146
- Initialize the KnowledgeAugmentedPromptAgent.
147
-
148
- Args:
149
- openai_api_key: The OpenAI API key for authentication.
150
- persona: The persona the agent should assume.
151
- knowledge: The specific knowledge to use for responses.
152
- base_url: Optional custom base URL for API calls.
153
- """
154
- self.openai_api_key = openai_api_key
155
  self.persona = persona
156
  self.knowledge = knowledge
157
- self.base_url = base_url
158
-
159
- def _get_client(self) -> OpenAI:
160
- """Create and return an OpenAI client instance."""
161
- if self.base_url:
162
- return OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
163
- return OpenAI(api_key=self.openai_api_key)
164
 
165
  def respond(self, input_text: str) -> str:
166
- """
167
- Generate a response using the persona and provided knowledge only.
168
-
169
- Args:
170
- input_text: The user's input prompt.
171
-
172
- Returns:
173
- The textual content of the LLM's response.
174
- """
175
  try:
176
- client = self._get_client()
177
-
178
  system_prompt = (
179
  f"You are {self.persona} knowledge-based assistant. Forget all previous context. "
180
  f"Use only the following knowledge to answer, do not use your own knowledge: {self.knowledge} "
181
  f"Answer the prompt based on this knowledge, not your own."
182
  )
183
-
184
- response = client.chat.completions.create(
185
- model="gpt-3.5-turbo",
186
- messages=[
187
- {"role": "system", "content": system_prompt},
188
- {"role": "user", "content": input_text}
189
- ],
190
- temperature=0
191
- )
192
-
193
- return response.choices[0].message.content
194
-
195
  except Exception as e:
196
  logger.error(f"KnowledgeAugmentedPromptAgent error: {str(e)}")
197
  raise
@@ -199,107 +256,68 @@ class KnowledgeAugmentedPromptAgent:
199
 
200
  class EvaluationAgent:
201
  """
202
- An Evaluation Agent that assesses responses from a worker agent
203
- against given criteria, potentially refining through iterative feedback.
204
-
205
- This agent implements a feedback loop to ensure quality outputs.
206
  """
207
-
208
  def __init__(
209
- self,
210
- openai_api_key: str,
211
- persona: str,
212
- evaluation_criteria: str,
213
- worker_agent: Any,
214
- max_interactions: int = 10,
215
- base_url: str = None
216
  ):
217
- """
218
- Initialize the EvaluationAgent.
219
-
220
- Args:
221
- openai_api_key: The OpenAI API key for authentication.
222
- persona: The evaluator's persona.
223
- evaluation_criteria: Criteria for evaluating responses.
224
- worker_agent: The agent whose responses will be evaluated.
225
- max_interactions: Maximum refinement iterations.
226
- base_url: Optional custom base URL for API calls.
227
- """
228
- self.openai_api_key = openai_api_key
229
  self.persona = persona
230
  self.evaluation_criteria = evaluation_criteria
231
  self.worker_agent = worker_agent
232
  self.max_interactions = max_interactions
233
- self.base_url = base_url
234
-
235
- def _get_client(self) -> OpenAI:
236
- """Create and return an OpenAI client instance."""
237
- if self.base_url:
238
- return OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
239
- return OpenAI(api_key=self.openai_api_key)
240
 
241
  def evaluate(self, prompt_to_evaluate: str) -> Dict[str, Any]:
242
- """
243
- Evaluate and potentially refine a response through iteration.
244
-
245
- Args:
246
- prompt_to_evaluate: The initial prompt to evaluate.
247
-
248
- Returns:
249
- Dictionary containing final_response, evaluation, and iterations.
250
- """
251
  try:
252
- client = self._get_client()
253
  initial_prompt = prompt_to_evaluate
254
  response_from_worker = ""
255
  evaluation = ""
256
-
257
  for i in range(self.max_interactions):
258
  logger.info(f"Evaluation iteration {i + 1}/{self.max_interactions}")
259
-
260
  # Step 1: Get response from worker agent
261
  response_from_worker = self.worker_agent.respond(prompt_to_evaluate)
262
-
263
  # Step 2: Evaluate the response
264
  eval_prompt = (
265
  f"Does the following answer: {response_from_worker}\n"
266
  f"Meet this criteria: {self.evaluation_criteria}\n"
267
  f"Respond Yes or No, and the reason why it does or doesn't meet the criteria."
268
  )
269
-
270
- response = client.chat.completions.create(
271
- model="gpt-3.5-turbo",
272
- messages=[
273
- {"role": "system", "content": self.persona},
274
- {"role": "user", "content": eval_prompt}
275
- ],
276
- temperature=0
277
- )
278
-
279
- evaluation = response.choices[0].message.content.strip()
280
-
281
  # Step 3: Check if evaluation passes
282
  if evaluation.lower().startswith("yes"):
283
  logger.info("Evaluation passed!")
284
  break
285
-
286
  # Step 4: Generate correction instructions
287
  instruction_prompt = (
288
  f"Provide instructions to fix an answer based on these reasons "
289
  f"why it is incorrect: {evaluation}"
290
  )
291
-
292
- response = client.chat.completions.create(
293
- model="gpt-3.5-turbo",
294
- messages=[
295
- {"role": "system", "content": "You are a helpful assistant that provides clear correction instructions."},
296
- {"role": "user", "content": instruction_prompt}
297
- ],
298
- temperature=0
299
- )
300
-
301
- instructions = response.choices[0].message.content.strip()
302
-
303
  # Step 5: Prepare refined prompt
304
  prompt_to_evaluate = (
305
  f"The original prompt was: {initial_prompt}\n"
@@ -307,13 +325,12 @@ class EvaluationAgent:
307
  f"It has been evaluated as incorrect.\n"
308
  f"Make only these corrections, do not alter content validity: {instructions}"
309
  )
310
-
311
  return {
312
  "final_response": response_from_worker,
313
  "evaluation": evaluation,
314
  "iterations": i + 1
315
  }
316
-
317
  except Exception as e:
318
  logger.error(f"EvaluationAgent error: {str(e)}")
319
  raise
@@ -321,114 +338,57 @@ class EvaluationAgent:
321
 
322
  class RoutingAgent:
323
  """
324
- A Routing Agent that directs user prompts to the most appropriate
325
- specialized agent based on semantic similarity.
326
-
327
- Uses embeddings to match prompts with agent descriptions.
328
  """
329
-
330
  def __init__(
331
- self,
332
- openai_api_key: str,
333
- agents: List[Dict[str, Any]],
334
- base_url: str = None
335
  ):
336
- """
337
- Initialize the RoutingAgent.
338
-
339
- Args:
340
- openai_api_key: The OpenAI API key for authentication.
341
- agents: List of agent dictionaries with name, description, and func.
342
- base_url: Optional custom base URL for API calls.
343
- """
344
- self.openai_api_key = openai_api_key
345
  self.agents = agents
346
- self.base_url = base_url
347
  self._embedding_cache = {}
348
 
349
- def _get_client(self) -> OpenAI:
350
- """Create and return an OpenAI client instance."""
351
- # Auto-detect Vocareum keys and use their base URL
352
- if self.openai_api_key and self.openai_api_key.startswith("voc-"):
353
- return OpenAI(
354
- api_key=self.openai_api_key,
355
- base_url="https://openai.vocareum.com/v1"
356
- )
357
- if self.base_url:
358
- return OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
359
- return OpenAI(api_key=self.openai_api_key)
360
-
361
  def get_embedding(self, text: str) -> List[float]:
362
- """
363
- Calculate the embedding of text using the text-embedding-3-large model.
364
-
365
- Args:
366
- text: The text to embed.
367
-
368
- Returns:
369
- The embedding vector.
370
- """
371
- # Check cache first
372
  if text in self._embedding_cache:
373
  return self._embedding_cache[text]
374
-
375
- try:
376
- client = self._get_client()
377
-
378
- response = client.embeddings.create(
379
- model="text-embedding-3-large",
380
- input=text,
381
- encoding_format="float"
382
- )
383
-
384
- embedding = response.data[0].embedding
385
- self._embedding_cache[text] = embedding
386
-
387
- return embedding
388
-
389
- except Exception as e:
390
- logger.error(f"Embedding error: {str(e)}")
391
- raise
392
 
393
  def route(self, user_input: str) -> Any:
394
- """
395
- Route user prompts to the most appropriate agent based on similarity.
396
-
397
- Args:
398
- user_input: The user's input prompt.
399
-
400
- Returns:
401
- The response from the selected agent's function.
402
- """
403
  try:
404
  input_emb = self.get_embedding(user_input)
405
  best_agent = None
406
  best_score = -1
407
-
408
  for agent in self.agents:
409
  agent_emb = self.get_embedding(agent["description"])
410
-
411
  if agent_emb is None:
412
  continue
413
-
414
  # Calculate cosine similarity
415
  similarity = np.dot(input_emb, agent_emb) / (
416
- np.linalg.norm(input_emb) * np.linalg.norm(agent_emb)
417
  )
418
-
419
  logger.info(f"Agent '{agent['name']}' similarity: {similarity:.3f}")
420
-
421
  if similarity > best_score:
422
  best_score = similarity
423
  best_agent = agent
424
-
425
  if best_agent is None:
426
  return "Sorry, no suitable agent could be selected."
427
-
428
  logger.info(f"Selected agent: {best_agent['name']} (score={best_score:.3f})")
429
-
430
  return best_agent["func"](user_input)
431
-
432
  except Exception as e:
433
  logger.error(f"RoutingAgent error: {str(e)}")
434
  raise
@@ -436,75 +396,40 @@ class RoutingAgent:
436
 
437
  class ActionPlanningAgent:
438
  """
439
- An Action Planning Agent that extracts and lists actionable steps
440
- from a user's prompt based on provided knowledge.
441
-
442
- Crucial for constructing agentic workflows by breaking down complex tasks.
443
  """
444
-
445
  def __init__(
446
- self,
447
- openai_api_key: str,
448
- knowledge: str,
449
- base_url: str = None
450
  ):
451
- """
452
- Initialize the ActionPlanningAgent.
453
-
454
- Args:
455
- openai_api_key: The OpenAI API key for authentication.
456
- knowledge: The knowledge base for extracting action steps.
457
- base_url: Optional custom base URL for API calls.
458
- """
459
- self.openai_api_key = openai_api_key
460
  self.knowledge = knowledge
461
- self.base_url = base_url
462
-
463
- def _get_client(self) -> OpenAI:
464
- """Create and return an OpenAI client instance."""
465
- if self.base_url:
466
- return OpenAI(api_key=self.openai_api_key, base_url=self.base_url)
467
- return OpenAI(api_key=self.openai_api_key)
468
 
469
  def extract_steps_from_prompt(self, prompt: str) -> List[str]:
470
- """
471
- Extract actionable steps from a user prompt using provided knowledge.
472
-
473
- Args:
474
- prompt: The user's input prompt describing a task.
475
-
476
- Returns:
477
- A clean list of action steps.
478
- """
479
  try:
480
- client = self._get_client()
481
-
482
  system_prompt = (
483
  f"You are an action planning agent. Using your knowledge, you extract from the user prompt "
484
  f"the steps requested to complete the action the user is asking for. You return the steps as a list. "
485
  f"Only return the steps in your knowledge. Forget any previous context. "
486
  f"This is your knowledge: {self.knowledge}"
487
  )
488
-
489
- response = client.chat.completions.create(
490
- model="gpt-3.5-turbo",
491
- messages=[
492
- {"role": "system", "content": system_prompt},
493
- {"role": "user", "content": prompt}
494
- ],
495
- temperature=0
496
- )
497
-
498
- response_text = response.choices[0].message.content
499
-
500
  # Clean and format the extracted steps
501
  steps = response_text.split("\n")
502
  cleaned_steps = [step.strip() for step in steps if step.strip()]
503
-
504
  logger.info(f"Extracted {len(cleaned_steps)} action steps")
505
-
506
  return cleaned_steps
507
-
508
  except Exception as e:
509
  logger.error(f"ActionPlanningAgent error: {str(e)}")
510
  raise
 
1
  """
2
  Base Agents Library for AI Project Planner
3
 
4
+ Supports multiple AI providers:
5
+ - OpenAI (sk-...)
6
+ - Anthropic Claude (sk-ant-...)
7
+ - Vocareum (voc-...)
8
+
9
+ Author: AI Workflow Architect
10
+ License: MIT
11
  """
12
 
13
  from openai import OpenAI
14
  import numpy as np
15
  from typing import Dict, Any, List, Optional, Callable
16
  import logging
17
+ import os
18
 
19
  # Configure logging
20
  logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger(__name__)
22
 
23
+ # Try to import Anthropic (optional)
24
+ try:
25
+ import anthropic
26
 
27
+ ANTHROPIC_AVAILABLE = True
28
+ except ImportError:
29
+ ANTHROPIC_AVAILABLE = False
30
+ logger.info("Anthropic SDK not installed. Claude support disabled.")
31
+
32
+
33
+ class AIProvider:
34
  """
35
+ Unified AI provider interface supporting multiple backends.
 
 
 
36
  """
37
+
38
+ def __init__(self, api_key: str, base_url: str = None):
39
+ self.api_key = api_key
 
 
 
 
 
 
 
40
  self.base_url = base_url
41
+ self.provider = self._detect_provider()
42
+ self.client = self._create_client()
 
 
 
 
43
 
44
+ def _detect_provider(self) -> str:
45
+ """Auto-detect the AI provider based on API key format."""
46
+ if not self.api_key:
47
+ raise ValueError("API key is required")
48
+
49
+ if self.api_key.startswith("sk-ant-"):
50
+ return "anthropic"
51
+ elif self.api_key.startswith("voc-"):
52
+ return "vocareum"
53
+ elif self.api_key.startswith("sk-"):
54
+ return "openai"
55
+ else:
56
+ # Default to OpenAI for unknown formats
57
+ return "openai"
58
+
59
+ def _create_client(self):
60
+ """Create the appropriate client based on provider."""
61
+ if self.provider == "anthropic":
62
+ if not ANTHROPIC_AVAILABLE:
63
+ raise ImportError("Anthropic SDK not installed. Run: pip install anthropic")
64
+ return anthropic.Anthropic(api_key=self.api_key)
65
+
66
+ elif self.provider == "vocareum":
67
+ return OpenAI(
68
+ api_key=self.api_key,
69
+ base_url="https://openai.vocareum.com/v1"
70
+ )
71
+
72
+ else: # openai
73
+ if self.base_url:
74
+ return OpenAI(api_key=self.api_key, base_url=self.base_url)
75
+ return OpenAI(api_key=self.api_key)
76
+
77
+ def chat_completion(
78
+ self,
79
+ messages: List[Dict[str, str]],
80
+ temperature: float = 0,
81
+ model: str = None
82
+ ) -> str:
83
  """
84
+ Generate a chat completion using the detected provider.
85
+
86
  Args:
87
+ messages: List of message dicts with 'role' and 'content'
88
+ temperature: Sampling temperature
89
+ model: Optional model override
90
+
91
  Returns:
92
+ The assistant's response text
93
+ """
94
+ if self.provider == "anthropic":
95
+ return self._anthropic_completion(messages, temperature, model)
96
+ else:
97
+ return self._openai_completion(messages, temperature, model)
98
+
99
+ def _openai_completion(
100
+ self,
101
+ messages: List[Dict[str, str]],
102
+ temperature: float,
103
+ model: str = None
104
+ ) -> str:
105
+ """OpenAI/Vocareum chat completion."""
106
+ model = model or "gpt-3.5-turbo"
107
+
108
+ response = self.client.chat.completions.create(
109
+ model=model,
110
+ messages=messages,
111
+ temperature=temperature
112
+ )
113
+ return response.choices[0].message.content
114
+
115
+ def _anthropic_completion(
116
+ self,
117
+ messages: List[Dict[str, str]],
118
+ temperature: float,
119
+ model: str = None
120
+ ) -> str:
121
+ """Anthropic Claude chat completion."""
122
+ model = model or "claude-3-haiku-20240307"
123
+
124
+ # Convert messages format for Anthropic
125
+ system_msg = ""
126
+ chat_messages = []
127
+
128
+ for msg in messages:
129
+ if msg["role"] == "system":
130
+ system_msg = msg["content"]
131
+ else:
132
+ chat_messages.append({
133
+ "role": msg["role"],
134
+ "content": msg["content"]
135
+ })
136
+
137
+ # Ensure messages alternate user/assistant
138
+ if chat_messages and chat_messages[0]["role"] != "user":
139
+ chat_messages.insert(0, {"role": "user", "content": "Hello"})
140
+
141
+ response = self.client.messages.create(
142
+ model=model,
143
+ max_tokens=4096,
144
+ system=system_msg if system_msg else "You are a helpful assistant.",
145
+ messages=chat_messages,
146
+ temperature=temperature
147
+ )
148
+ return response.content[0].text
149
+
150
+ def get_embedding(self, text: str) -> List[float]:
151
  """
152
+ Get text embedding. Only supported for OpenAI/Vocareum.
153
+ For Anthropic, falls back to a simple hash-based embedding.
154
+ """
155
+ if self.provider == "anthropic":
156
+ # Anthropic doesn't have embeddings API
157
+ # Use a simple fallback for routing
158
+ logger.warning("Embeddings not available for Anthropic. Using fallback.")
159
+ return self._fallback_embedding(text)
160
+
161
+ response = self.client.embeddings.create(
162
+ model="text-embedding-3-large",
163
+ input=text,
164
+ encoding_format="float"
165
+ )
166
+ return response.data[0].embedding
167
+
168
+ def _fallback_embedding(self, text: str) -> List[float]:
169
+ """Simple fallback embedding using character frequencies."""
170
+ # Create a basic 256-dim embedding based on character frequencies
171
+ embedding = [0.0] * 256
172
+ for char in text.lower():
173
+ idx = ord(char) % 256
174
+ embedding[idx] += 1
175
+ # Normalize
176
+ total = sum(embedding) or 1
177
+ return [x / total for x in embedding]
178
+
179
+
180
+ class DirectPromptAgent:
181
+ """
182
+ A Direct Prompt Agent that relays user input directly to the LLM.
183
+ """
184
+
185
+ def __init__(self, openai_api_key: str, base_url: str = None):
186
+ self.provider = AIProvider(openai_api_key, base_url)
187
+
188
+ def respond(self, prompt: str) -> str:
189
+ """Generate a response by passing the user prompt directly to the LLM."""
190
  try:
191
+ messages = [{"role": "user", "content": prompt}]
192
+ return self.provider.chat_completion(messages, temperature=0)
 
 
 
 
 
 
 
 
 
 
193
  except Exception as e:
194
  logger.error(f"DirectPromptAgent error: {str(e)}")
195
  raise
 
198
  class AugmentedPromptAgent:
199
  """
200
  An Augmented Prompt Agent that responds according to a predefined persona.
 
 
 
201
  """
202
+
203
  def __init__(self, openai_api_key: str, persona: str, base_url: str = None):
204
+ self.provider = AIProvider(openai_api_key, base_url)
 
 
 
 
 
 
 
 
205
  self.persona = persona
 
 
 
 
 
 
 
206
 
207
  def respond(self, input_text: str) -> str:
208
+ """Generate a response using the defined persona."""
 
 
 
 
 
 
 
 
209
  try:
 
 
210
  system_prompt = f"{self.persona} Forget all previous conversational context."
211
+
212
+ messages = [
213
+ {"role": "system", "content": system_prompt},
214
+ {"role": "user", "content": input_text}
215
+ ]
216
+ return self.provider.chat_completion(messages, temperature=1.0)
 
 
 
 
 
 
217
  except Exception as e:
218
  logger.error(f"AugmentedPromptAgent error: {str(e)}")
219
  raise
 
221
 
222
  class KnowledgeAugmentedPromptAgent:
223
  """
224
+ A Knowledge Augmented Prompt Agent that uses specific knowledge with a persona.
 
 
 
 
225
  """
226
+
227
  def __init__(
228
+ self,
229
+ openai_api_key: str,
230
+ persona: str,
231
+ knowledge: str,
232
+ base_url: str = None
233
  ):
234
+ self.provider = AIProvider(openai_api_key, base_url)
 
 
 
 
 
 
 
 
 
235
  self.persona = persona
236
  self.knowledge = knowledge
 
 
 
 
 
 
 
237
 
238
  def respond(self, input_text: str) -> str:
239
+ """Generate a response using the persona and provided knowledge."""
 
 
 
 
 
 
 
 
240
  try:
 
 
241
  system_prompt = (
242
  f"You are {self.persona} knowledge-based assistant. Forget all previous context. "
243
  f"Use only the following knowledge to answer, do not use your own knowledge: {self.knowledge} "
244
  f"Answer the prompt based on this knowledge, not your own."
245
  )
246
+
247
+ messages = [
248
+ {"role": "system", "content": system_prompt},
249
+ {"role": "user", "content": input_text}
250
+ ]
251
+ return self.provider.chat_completion(messages, temperature=0)
 
 
 
 
 
 
252
  except Exception as e:
253
  logger.error(f"KnowledgeAugmentedPromptAgent error: {str(e)}")
254
  raise
 
256
 
257
  class EvaluationAgent:
258
  """
259
+ An Evaluation Agent that assesses and refines responses iteratively.
 
 
 
260
  """
261
+
262
  def __init__(
263
+ self,
264
+ openai_api_key: str,
265
+ persona: str,
266
+ evaluation_criteria: str,
267
+ worker_agent: Any,
268
+ max_interactions: int = 10,
269
+ base_url: str = None
270
  ):
271
+ self.provider = AIProvider(openai_api_key, base_url)
 
 
 
 
 
 
 
 
 
 
 
272
  self.persona = persona
273
  self.evaluation_criteria = evaluation_criteria
274
  self.worker_agent = worker_agent
275
  self.max_interactions = max_interactions
 
 
 
 
 
 
 
276
 
277
  def evaluate(self, prompt_to_evaluate: str) -> Dict[str, Any]:
278
+ """Evaluate and potentially refine a response through iteration."""
 
 
 
 
 
 
 
 
279
  try:
 
280
  initial_prompt = prompt_to_evaluate
281
  response_from_worker = ""
282
  evaluation = ""
283
+
284
  for i in range(self.max_interactions):
285
  logger.info(f"Evaluation iteration {i + 1}/{self.max_interactions}")
286
+
287
  # Step 1: Get response from worker agent
288
  response_from_worker = self.worker_agent.respond(prompt_to_evaluate)
289
+
290
  # Step 2: Evaluate the response
291
  eval_prompt = (
292
  f"Does the following answer: {response_from_worker}\n"
293
  f"Meet this criteria: {self.evaluation_criteria}\n"
294
  f"Respond Yes or No, and the reason why it does or doesn't meet the criteria."
295
  )
296
+
297
+ messages = [
298
+ {"role": "system", "content": self.persona},
299
+ {"role": "user", "content": eval_prompt}
300
+ ]
301
+ evaluation = self.provider.chat_completion(messages, temperature=0)
302
+
 
 
 
 
 
303
  # Step 3: Check if evaluation passes
304
  if evaluation.lower().startswith("yes"):
305
  logger.info("Evaluation passed!")
306
  break
307
+
308
  # Step 4: Generate correction instructions
309
  instruction_prompt = (
310
  f"Provide instructions to fix an answer based on these reasons "
311
  f"why it is incorrect: {evaluation}"
312
  )
313
+
314
+ messages = [
315
+ {"role": "system",
316
+ "content": "You are a helpful assistant that provides clear correction instructions."},
317
+ {"role": "user", "content": instruction_prompt}
318
+ ]
319
+ instructions = self.provider.chat_completion(messages, temperature=0)
320
+
 
 
 
 
321
  # Step 5: Prepare refined prompt
322
  prompt_to_evaluate = (
323
  f"The original prompt was: {initial_prompt}\n"
 
325
  f"It has been evaluated as incorrect.\n"
326
  f"Make only these corrections, do not alter content validity: {instructions}"
327
  )
328
+
329
  return {
330
  "final_response": response_from_worker,
331
  "evaluation": evaluation,
332
  "iterations": i + 1
333
  }
 
334
  except Exception as e:
335
  logger.error(f"EvaluationAgent error: {str(e)}")
336
  raise
 
338
 
339
  class RoutingAgent:
340
  """
341
+ A Routing Agent that directs prompts to appropriate specialized agents.
 
 
 
342
  """
343
+
344
  def __init__(
345
+ self,
346
+ openai_api_key: str,
347
+ agents: List[Dict[str, Any]],
348
+ base_url: str = None
349
  ):
350
+ self.provider = AIProvider(openai_api_key, base_url)
 
 
 
 
 
 
 
 
351
  self.agents = agents
 
352
  self._embedding_cache = {}
353
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  def get_embedding(self, text: str) -> List[float]:
355
+ """Get embedding with caching."""
 
 
 
 
 
 
 
 
 
356
  if text in self._embedding_cache:
357
  return self._embedding_cache[text]
358
+
359
+ embedding = self.provider.get_embedding(text)
360
+ self._embedding_cache[text] = embedding
361
+ return embedding
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
 
363
  def route(self, user_input: str) -> Any:
364
+ """Route user prompts to the most appropriate agent."""
 
 
 
 
 
 
 
 
365
  try:
366
  input_emb = self.get_embedding(user_input)
367
  best_agent = None
368
  best_score = -1
369
+
370
  for agent in self.agents:
371
  agent_emb = self.get_embedding(agent["description"])
372
+
373
  if agent_emb is None:
374
  continue
375
+
376
  # Calculate cosine similarity
377
  similarity = np.dot(input_emb, agent_emb) / (
378
+ np.linalg.norm(input_emb) * np.linalg.norm(agent_emb)
379
  )
380
+
381
  logger.info(f"Agent '{agent['name']}' similarity: {similarity:.3f}")
382
+
383
  if similarity > best_score:
384
  best_score = similarity
385
  best_agent = agent
386
+
387
  if best_agent is None:
388
  return "Sorry, no suitable agent could be selected."
389
+
390
  logger.info(f"Selected agent: {best_agent['name']} (score={best_score:.3f})")
 
391
  return best_agent["func"](user_input)
 
392
  except Exception as e:
393
  logger.error(f"RoutingAgent error: {str(e)}")
394
  raise
 
396
 
397
  class ActionPlanningAgent:
398
  """
399
+ An Action Planning Agent that extracts actionable steps from prompts.
 
 
 
400
  """
401
+
402
  def __init__(
403
+ self,
404
+ openai_api_key: str,
405
+ knowledge: str,
406
+ base_url: str = None
407
  ):
408
+ self.provider = AIProvider(openai_api_key, base_url)
 
 
 
 
 
 
 
 
409
  self.knowledge = knowledge
 
 
 
 
 
 
 
410
 
411
  def extract_steps_from_prompt(self, prompt: str) -> List[str]:
412
+ """Extract actionable steps from a user prompt."""
 
 
 
 
 
 
 
 
413
  try:
 
 
414
  system_prompt = (
415
  f"You are an action planning agent. Using your knowledge, you extract from the user prompt "
416
  f"the steps requested to complete the action the user is asking for. You return the steps as a list. "
417
  f"Only return the steps in your knowledge. Forget any previous context. "
418
  f"This is your knowledge: {self.knowledge}"
419
  )
420
+
421
+ messages = [
422
+ {"role": "system", "content": system_prompt},
423
+ {"role": "user", "content": prompt}
424
+ ]
425
+ response_text = self.provider.chat_completion(messages, temperature=0)
426
+
 
 
 
 
 
427
  # Clean and format the extracted steps
428
  steps = response_text.split("\n")
429
  cleaned_steps = [step.strip() for step in steps if step.strip()]
430
+
431
  logger.info(f"Extracted {len(cleaned_steps)} action steps")
 
432
  return cleaned_steps
 
433
  except Exception as e:
434
  logger.error(f"ActionPlanningAgent error: {str(e)}")
435
  raise
requirements.txt CHANGED
@@ -1,8 +1,5 @@
1
- # AI Project Planner - Dependencies
2
- # For Hugging Face Spaces deployment
3
-
4
- # Core Framework
5
  gradio==4.44.0
6
  openai>=1.0.0
 
7
  numpy>=1.24.0
8
  python-dotenv>=1.0.0
 
 
 
 
 
1
  gradio==4.44.0
2
  openai>=1.0.0
3
+ anthropic>=0.18.0
4
  numpy>=1.24.0
5
  python-dotenv>=1.0.0