File size: 15,617 Bytes
ea1c770
 
 
a87ed52
 
 
 
 
 
 
ea1c770
 
 
 
 
 
a87ed52
ea1c770
 
 
 
 
a87ed52
 
 
ea1c770
a87ed52
 
 
 
 
 
 
ea1c770
a87ed52
ea1c770
a87ed52
 
 
ea1c770
a87ed52
 
ea1c770
a87ed52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea1c770
a87ed52
 
ea1c770
a87ed52
 
 
 
ea1c770
a87ed52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea1c770
a87ed52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea1c770
a87ed52
 
ea1c770
 
 
 
 
 
 
 
 
a87ed52
ea1c770
a87ed52
ea1c770
 
 
a87ed52
ea1c770
 
a87ed52
 
 
 
 
 
ea1c770
 
 
 
 
 
 
a87ed52
ea1c770
a87ed52
ea1c770
a87ed52
 
 
 
 
ea1c770
a87ed52
ea1c770
 
 
 
a87ed52
ea1c770
 
 
 
 
 
a87ed52
 
 
 
 
 
ea1c770
 
 
 
 
 
 
a87ed52
ea1c770
a87ed52
ea1c770
a87ed52
 
 
 
 
 
 
ea1c770
a87ed52
ea1c770
 
 
 
 
 
a87ed52
ea1c770
 
 
 
a87ed52
ea1c770
 
a87ed52
ea1c770
 
a87ed52
ea1c770
 
 
 
 
 
a87ed52
 
 
 
 
 
 
ea1c770
 
 
 
a87ed52
ea1c770
 
 
 
 
a87ed52
 
 
 
 
 
 
 
ea1c770
 
 
 
 
 
 
a87ed52
ea1c770
 
 
 
 
 
 
 
 
 
 
 
a87ed52
ea1c770
a87ed52
ea1c770
a87ed52
 
 
 
ea1c770
a87ed52
ea1c770
 
7d69d21
ea1c770
a87ed52
ea1c770
 
a87ed52
 
 
 
ea1c770
 
a87ed52
ea1c770
 
 
 
a87ed52
ea1c770
 
a87ed52
ea1c770
 
a87ed52
ea1c770
 
a87ed52
ea1c770
a87ed52
ea1c770
a87ed52
ea1c770
 
 
a87ed52
ea1c770
 
a87ed52
ea1c770
 
 
 
 
 
 
 
 
a87ed52
ea1c770
a87ed52
ea1c770
a87ed52
 
 
 
ea1c770
a87ed52
ea1c770
 
 
a87ed52
ea1c770
 
 
 
 
 
 
a87ed52
 
 
 
 
 
 
ea1c770
 
 
a87ed52
ea1c770
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
"""
Base Agents Library for AI Project Planner

Supports multiple AI providers:
- OpenAI (sk-...)
- Anthropic Claude (sk-ant-...)
- Vocareum (voc-...)

Author: AI Workflow Architect
License: MIT
"""

from openai import OpenAI
import numpy as np
from typing import Dict, Any, List, Optional, Callable
import logging
import os

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Try to import Anthropic (optional)
try:
    import anthropic

    ANTHROPIC_AVAILABLE = True
except ImportError:
    ANTHROPIC_AVAILABLE = False
    logger.info("Anthropic SDK not installed. Claude support disabled.")


class AIProvider:
    """
    Unified AI provider interface supporting multiple backends.
    """

    def __init__(self, api_key: str, base_url: str = None):
        self.api_key = api_key
        self.base_url = base_url
        self.provider = self._detect_provider()
        self.client = self._create_client()

    def _detect_provider(self) -> str:
        """Auto-detect the AI provider based on API key format."""
        if not self.api_key:
            raise ValueError("API key is required")

        if self.api_key.startswith("sk-ant-"):
            return "anthropic"
        elif self.api_key.startswith("voc-"):
            return "vocareum"
        elif self.api_key.startswith("sk-"):
            return "openai"
        else:
            # Default to OpenAI for unknown formats
            return "openai"

    def _create_client(self):
        """Create the appropriate client based on provider."""
        if self.provider == "anthropic":
            if not ANTHROPIC_AVAILABLE:
                raise ImportError("Anthropic SDK not installed. Run: pip install anthropic")
            return anthropic.Anthropic(api_key=self.api_key)

        elif self.provider == "vocareum":
            return OpenAI(
                api_key=self.api_key,
                base_url="https://openai.vocareum.com/v1"
            )

        else:  # openai
            if self.base_url:
                return OpenAI(api_key=self.api_key, base_url=self.base_url)
            return OpenAI(api_key=self.api_key)

    def chat_completion(
            self,
            messages: List[Dict[str, str]],
            temperature: float = 0,
            model: str = None
    ) -> str:
        """
        Generate a chat completion using the detected provider.

        Args:
            messages: List of message dicts with 'role' and 'content'
            temperature: Sampling temperature
            model: Optional model override

        Returns:
            The assistant's response text
        """
        if self.provider == "anthropic":
            return self._anthropic_completion(messages, temperature, model)
        else:
            return self._openai_completion(messages, temperature, model)

    def _openai_completion(
            self,
            messages: List[Dict[str, str]],
            temperature: float,
            model: str = None
    ) -> str:
        """OpenAI/Vocareum chat completion."""
        model = model or "gpt-3.5-turbo"

        response = self.client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature
        )
        return response.choices[0].message.content

    def _anthropic_completion(
            self,
            messages: List[Dict[str, str]],
            temperature: float,
            model: str = None
    ) -> str:
        """Anthropic Claude chat completion."""
        model = model or "claude-3-haiku-20240307"

        # Convert messages format for Anthropic
        system_msg = ""
        chat_messages = []

        for msg in messages:
            if msg["role"] == "system":
                system_msg = msg["content"]
            else:
                chat_messages.append({
                    "role": msg["role"],
                    "content": msg["content"]
                })

        # Ensure messages alternate user/assistant
        if chat_messages and chat_messages[0]["role"] != "user":
            chat_messages.insert(0, {"role": "user", "content": "Hello"})

        response = self.client.messages.create(
            model=model,
            max_tokens=4096,
            system=system_msg if system_msg else "You are a helpful assistant.",
            messages=chat_messages,
            temperature=temperature
        )
        return response.content[0].text

    def get_embedding(self, text: str) -> List[float]:
        """
        Get text embedding. Only supported for OpenAI/Vocareum.
        For Anthropic, falls back to a simple hash-based embedding.
        """
        if self.provider == "anthropic":
            # Anthropic doesn't have embeddings API
            # Use a simple fallback for routing
            logger.warning("Embeddings not available for Anthropic. Using fallback.")
            return self._fallback_embedding(text)

        response = self.client.embeddings.create(
            model="text-embedding-3-large",
            input=text,
            encoding_format="float"
        )
        return response.data[0].embedding

    def _fallback_embedding(self, text: str) -> List[float]:
        """Simple fallback embedding using character frequencies."""
        # Create a basic 256-dim embedding based on character frequencies
        embedding = [0.0] * 256
        for char in text.lower():
            idx = ord(char) % 256
            embedding[idx] += 1
        # Normalize
        total = sum(embedding) or 1
        return [x / total for x in embedding]


class DirectPromptAgent:
    """
    A Direct Prompt Agent that relays user input directly to the LLM.
    """

    def __init__(self, openai_api_key: str, base_url: str = None):
        self.provider = AIProvider(openai_api_key, base_url)

    def respond(self, prompt: str) -> str:
        """Generate a response by passing the user prompt directly to the LLM."""
        try:
            messages = [{"role": "user", "content": prompt}]
            return self.provider.chat_completion(messages, temperature=0)
        except Exception as e:
            logger.error(f"DirectPromptAgent error: {str(e)}")
            raise


class AugmentedPromptAgent:
    """
    An Augmented Prompt Agent that responds according to a predefined persona.
    """

    def __init__(self, openai_api_key: str, persona: str, base_url: str = None):
        self.provider = AIProvider(openai_api_key, base_url)
        self.persona = persona

    def respond(self, input_text: str) -> str:
        """Generate a response using the defined persona."""
        try:
            system_prompt = f"{self.persona} Forget all previous conversational context."

            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": input_text}
            ]
            return self.provider.chat_completion(messages, temperature=1.0)
        except Exception as e:
            logger.error(f"AugmentedPromptAgent error: {str(e)}")
            raise


class KnowledgeAugmentedPromptAgent:
    """
    A Knowledge Augmented Prompt Agent that uses specific knowledge with a persona.
    """

    def __init__(
            self,
            openai_api_key: str,
            persona: str,
            knowledge: str,
            base_url: str = None
    ):
        self.provider = AIProvider(openai_api_key, base_url)
        self.persona = persona
        self.knowledge = knowledge

    def respond(self, input_text: str) -> str:
        """Generate a response using the persona and provided knowledge."""
        try:
            system_prompt = (
                f"You are {self.persona} knowledge-based assistant. Forget all previous context. "
                f"Use only the following knowledge to answer, do not use your own knowledge: {self.knowledge} "
                f"Answer the prompt based on this knowledge, not your own."
            )

            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": input_text}
            ]
            return self.provider.chat_completion(messages, temperature=0)
        except Exception as e:
            logger.error(f"KnowledgeAugmentedPromptAgent error: {str(e)}")
            raise


class EvaluationAgent:
    """
    An Evaluation Agent that assesses and refines responses iteratively.
    """

    def __init__(
            self,
            openai_api_key: str,
            persona: str,
            evaluation_criteria: str,
            worker_agent: Any,
            max_interactions: int = 10,
            base_url: str = None
    ):
        self.provider = AIProvider(openai_api_key, base_url)
        self.persona = persona
        self.evaluation_criteria = evaluation_criteria
        self.worker_agent = worker_agent
        self.max_interactions = max_interactions

    def evaluate(self, prompt_to_evaluate: str) -> Dict[str, Any]:
        """Evaluate and potentially refine a response through iteration."""
        try:
            initial_prompt = prompt_to_evaluate
            response_from_worker = ""
            evaluation = ""

            for i in range(self.max_interactions):
                logger.info(f"Evaluation iteration {i + 1}/{self.max_interactions}")

                # Step 1: Get response from worker agent
                response_from_worker = self.worker_agent.respond(prompt_to_evaluate)

                # Step 2: Evaluate the response
                eval_prompt = (
                    f"Does the following answer: {response_from_worker}\n"
                    f"Meet this criteria: {self.evaluation_criteria}\n"
                    f"Respond Yes or No, and the reason why it does or doesn't meet the criteria."
                )

                messages = [
                    {"role": "system", "content": self.persona},
                    {"role": "user", "content": eval_prompt}
                ]
                evaluation = self.provider.chat_completion(messages, temperature=0)

                # Step 3: Check if evaluation passes
                if evaluation.lower().startswith("yes"):
                    logger.info("Evaluation passed!")
                    break

                # Step 4: Generate correction instructions
                instruction_prompt = (
                    f"Provide instructions to fix an answer based on these reasons "
                    f"why it is incorrect: {evaluation}"
                )

                messages = [
                    {"role": "system",
                     "content": "You are a helpful assistant that provides clear correction instructions."},
                    {"role": "user", "content": instruction_prompt}
                ]
                instructions = self.provider.chat_completion(messages, temperature=0)

                # Step 5: Prepare refined prompt
                prompt_to_evaluate = (
                    f"The original prompt was: {initial_prompt}\n"
                    f"The response to that prompt was: {response_from_worker}\n"
                    f"It has been evaluated as incorrect.\n"
                    f"Make only these corrections, do not alter content validity: {instructions}"
                )

            return {
                "final_response": response_from_worker,
                "evaluation": evaluation,
                "iterations": i + 1
            }
        except Exception as e:
            logger.error(f"EvaluationAgent error: {str(e)}")
            raise


class RoutingAgent:
    """
    A Routing Agent that directs prompts to appropriate specialized agents.
    """

    def __init__(
            self,
            openai_api_key: str,
            agents: List[Dict[str, Any]],
            base_url: str = None
    ):
        self.provider = AIProvider(openai_api_key, base_url)
        self.agents = agents
        self._embedding_cache = {}

    def get_embedding(self, text: str) -> List[float]:
        """Get embedding with caching."""
        if text in self._embedding_cache:
            return self._embedding_cache[text]

        embedding = self.provider.get_embedding(text)
        self._embedding_cache[text] = embedding
        return embedding

    def route(self, user_input: str) -> Any:
        """Route user prompts to the most appropriate agent."""
        try:
            input_emb = self.get_embedding(user_input)
            best_agent = None
            best_score = -1

            for agent in self.agents:
                agent_emb = self.get_embedding(agent["description"])

                if agent_emb is None:
                    continue

                # Calculate cosine similarity
                similarity = np.dot(input_emb, agent_emb) / (
                        np.linalg.norm(input_emb) * np.linalg.norm(agent_emb)
                )

                logger.info(f"Agent '{agent['name']}' similarity: {similarity:.3f}")

                if similarity > best_score:
                    best_score = similarity
                    best_agent = agent

            if best_agent is None:
                return "Sorry, no suitable agent could be selected."

            logger.info(f"Selected agent: {best_agent['name']} (score={best_score:.3f})")
            return best_agent["func"](user_input)
        except Exception as e:
            logger.error(f"RoutingAgent error: {str(e)}")
            raise


class ActionPlanningAgent:
    """
    An Action Planning Agent that extracts actionable steps from prompts.
    """

    def __init__(
            self,
            openai_api_key: str,
            knowledge: str,
            base_url: str = None
    ):
        self.provider = AIProvider(openai_api_key, base_url)
        self.knowledge = knowledge

    def extract_steps_from_prompt(self, prompt: str) -> List[str]:
        """Extract actionable steps from a user prompt."""
        try:
            system_prompt = (
                f"You are an action planning agent. Using your knowledge, you extract from the user prompt "
                f"the steps requested to complete the action the user is asking for. You return the steps as a list. "
                f"Only return the steps in your knowledge. Forget any previous context. "
                f"This is your knowledge: {self.knowledge}"
            )

            messages = [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": prompt}
            ]
            response_text = self.provider.chat_completion(messages, temperature=0)

            # Clean and format the extracted steps
            steps = response_text.split("\n")
            cleaned_steps = [step.strip() for step in steps if step.strip()]

            logger.info(f"Extracted {len(cleaned_steps)} action steps")
            return cleaned_steps
        except Exception as e:
            logger.error(f"ActionPlanningAgent error: {str(e)}")
            raise


# ============================================================================
# UTILITY FUNCTIONS
# ============================================================================

def cosine_similarity(vec1: List[float], vec2: List[float]) -> float:
    """
    Calculate cosine similarity between two vectors.
    
    Args:
        vec1: First vector.
        vec2: Second vector.
        
    Returns:
        Cosine similarity score between 0 and 1.
    """
    vec1 = np.array(vec1)
    vec2 = np.array(vec2)
    
    return np.dot(vec1, vec2) / (np.linalg.norm(vec1) * np.linalg.norm(vec2))