agent-squad 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. agent_squad/__init__.py +3 -0
  2. agent_squad/agents/__init__.py +81 -0
  3. agent_squad/agents/agent.py +181 -0
  4. agent_squad/agents/amazon_bedrock_agent.py +172 -0
  5. agent_squad/agents/anthropic_agent.py +331 -0
  6. agent_squad/agents/bedrock_flows_agent.py +115 -0
  7. agent_squad/agents/bedrock_inline_agent.py +346 -0
  8. agent_squad/agents/bedrock_llm_agent.py +376 -0
  9. agent_squad/agents/bedrock_translator_agent.py +139 -0
  10. agent_squad/agents/chain_agent.py +86 -0
  11. agent_squad/agents/comprehend_filter_agent.py +163 -0
  12. agent_squad/agents/lambda_agent.py +86 -0
  13. agent_squad/agents/lex_bot_agent.py +71 -0
  14. agent_squad/agents/openai_agent.py +211 -0
  15. agent_squad/agents/supervisor_agent.py +290 -0
  16. agent_squad/classifiers/__init__.py +45 -0
  17. agent_squad/classifiers/anthropic_classifier.py +100 -0
  18. agent_squad/classifiers/bedrock_classifier.py +136 -0
  19. agent_squad/classifiers/classifier.py +181 -0
  20. agent_squad/classifiers/openai_classifier.py +108 -0
  21. agent_squad/orchestrator.py +349 -0
  22. agent_squad/retrievers/__init__.py +8 -0
  23. agent_squad/retrievers/amazon_kb_retriever.py +55 -0
  24. agent_squad/retrievers/retriever.py +61 -0
  25. agent_squad/shared/__init__.py +0 -0
  26. agent_squad/shared/user_agent.py +208 -0
  27. agent_squad/shared/version.py +3 -0
  28. agent_squad/storage/__init__.py +35 -0
  29. agent_squad/storage/chat_storage.py +121 -0
  30. agent_squad/storage/dynamodb_chat_storage.py +209 -0
  31. agent_squad/storage/in_memory_chat_storage.py +116 -0
  32. agent_squad/storage/sql_chat_storage.py +302 -0
  33. agent_squad/types/__init__.py +36 -0
  34. agent_squad/types/types.py +74 -0
  35. agent_squad/utils/__init__.py +12 -0
  36. agent_squad/utils/helpers.py +34 -0
  37. agent_squad/utils/logger.py +106 -0
  38. agent_squad/utils/tool.py +256 -0
  39. agent_squad-1.0.0.dist-info/METADATA +302 -0
  40. agent_squad-1.0.0.dist-info/RECORD +43 -0
  41. agent_squad-1.0.0.dist-info/WHEEL +5 -0
  42. agent_squad-1.0.0.dist-info/licenses/LICENSE +202 -0
  43. agent_squad-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,3 @@
1
+ from .shared import user_agent
2
+
3
+ user_agent.inject_user_agent()
@@ -0,0 +1,81 @@
1
+ """
2
+ Code for Agents.
3
+ """
4
+ from .agent import Agent, AgentOptions, AgentCallbacks, AgentProcessingResult, AgentResponse, AgentStreamResponse
5
+
6
+
7
+ try:
8
+ from .lambda_agent import LambdaAgent, LambdaAgentOptions
9
+ from .bedrock_llm_agent import BedrockLLMAgent, BedrockLLMAgentOptions
10
+ from .lex_bot_agent import LexBotAgent, LexBotAgentOptions
11
+ from .amazon_bedrock_agent import AmazonBedrockAgent, AmazonBedrockAgentOptions
12
+ from .comprehend_filter_agent import ComprehendFilterAgent, ComprehendFilterAgentOptions
13
+ from .bedrock_translator_agent import BedrockTranslatorAgent, BedrockTranslatorAgentOptions
14
+ from .chain_agent import ChainAgent, ChainAgentOptions
15
+ from .bedrock_inline_agent import BedrockInlineAgent, BedrockInlineAgentOptions
16
+ from .bedrock_flows_agent import BedrockFlowsAgent, BedrockFlowsAgentOptions
17
+ _AWS_AVAILABLE = True
18
+ except ImportError:
19
+ _AWS_AVAILABLE = False
20
+ try:
21
+ from .anthropic_agent import AnthropicAgent, AnthropicAgentOptions
22
+ _ANTHROPIC_AVAILABLE = True
23
+ except ImportError:
24
+ _ANTHROPIC_AVAILABLE = False
25
+
26
+
27
+ try:
28
+ from .openai_agent import OpenAIAgent, OpenAIAgentOptions
29
+ _OPENAI_AVAILABLE = True
30
+ except ImportError:
31
+ _OPENAI_AVAILABLE = False
32
+
33
+ from .supervisor_agent import SupervisorAgent, SupervisorAgentOptions
34
+
35
+ __all__ = [
36
+ 'Agent',
37
+ 'AgentOptions',
38
+ 'AgentCallbacks',
39
+ 'AgentProcessingResult',
40
+ 'AgentResponse',
41
+ 'AgentStreamResponse',
42
+ 'SupervisorAgent',
43
+ 'SupervisorAgentOptions'
44
+ ]
45
+
46
+
47
+ if _AWS_AVAILABLE :
48
+ __all__.extend([
49
+ 'LambdaAgent',
50
+ 'LambdaAgentOptions',
51
+ 'BedrockLLMAgent',
52
+ 'BedrockLLMAgentOptions',
53
+ 'LexBotAgent',
54
+ 'LexBotAgentOptions',
55
+ 'AmazonBedrockAgent',
56
+ 'AmazonBedrockAgentOptions',
57
+ 'ComprehendFilterAgent',
58
+ 'ComprehendFilterAgentOptions',
59
+ 'ChainAgent',
60
+ 'ChainAgentOptions',
61
+ 'BedrockTranslatorAgent',
62
+ 'BedrockTranslatorAgentOptions',
63
+ 'BedrockInlineAgent',
64
+ 'BedrockInlineAgentOptions',
65
+ 'BedrockFlowsAgent',
66
+ 'BedrockFlowsAgentOptions'
67
+ ])
68
+
69
+
70
+ if _ANTHROPIC_AVAILABLE:
71
+ __all__.extend([
72
+ 'AnthropicAgent',
73
+ 'AnthropicAgentOptions'
74
+ ])
75
+
76
+
77
+ if _OPENAI_AVAILABLE:
78
+ __all__.extend([
79
+ 'OpenAIAgent',
80
+ 'OpenAIAgentOptions'
81
+ ])
@@ -0,0 +1,181 @@
1
+ from typing import Union, AsyncIterable, Optional, Any, TypeAlias
2
+ import re
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass, field
5
+ from agent_squad.types import ConversationMessage
6
+ from agent_squad.utils import Logger
7
+
8
+ # Type aliases for complex types
9
+ AgentParamsType: TypeAlias = dict[str, Any]
10
+ AgentOutputType: TypeAlias = Union[str, "AgentStreamResponse", Any] # Forward reference
11
+
12
+ @dataclass
13
+ class AgentProcessingResult:
14
+ """
15
+ Contains metadata about the result of an agent's processing.
16
+
17
+ Attributes:
18
+ user_input: The original input from the user
19
+ agent_id: Unique identifier for the agent
20
+ agent_name: Display name of the agent
21
+ user_id: Identifier for the user
22
+ session_id: Identifier for the current session
23
+ additional_params: Optional additional parameters for the agent
24
+ """
25
+ user_input: str
26
+ agent_id: str
27
+ agent_name: str
28
+ user_id: str
29
+ session_id: str
30
+ additional_params: AgentParamsType = field(default_factory=dict)
31
+
32
+
33
+ @dataclass
34
+ class AgentStreamResponse:
35
+ """
36
+ Represents a streaming response from an agent.
37
+
38
+ Attributes:
39
+ text: The current text in the stream
40
+ final_message: The complete message when streaming is complete
41
+ """
42
+ text: str = ""
43
+ final_message: Optional[ConversationMessage] = None
44
+
45
+
46
+ @dataclass
47
+ class AgentResponse:
48
+ """
49
+ Complete response from an agent, including metadata and output.
50
+
51
+ Attributes:
52
+ metadata: Processing metadata
53
+ output: The actual output from the agent
54
+ streaming: Whether this response is streaming
55
+ """
56
+ metadata: AgentProcessingResult
57
+ output: AgentOutputType
58
+ streaming: bool
59
+
60
+
61
+ class AgentCallbacks:
62
+ """
63
+ Defines callbacks that can be triggered during agent processing.
64
+ Provides default implementations that can be overridden by subclasses.
65
+ """
66
+ def on_llm_new_token(self, token: str) -> None:
67
+ """
68
+ Called when a new token is generated by the LLM.
69
+
70
+ Args:
71
+ token: The new token generated
72
+ """
73
+ pass # Default implementation does nothing
74
+
75
+
76
+ @dataclass
77
+ class AgentOptions:
78
+ """
79
+ Configuration options for an agent.
80
+
81
+ Attributes:
82
+ name: The display name of the agent
83
+ description: A description of the agent's purpose and capabilities
84
+ save_chat: Whether to save the chat history
85
+ callbacks: Optional callbacks for agent events
86
+ LOG_AGENT_DEBUG_TRACE: Whether to enable debug tracing for this agent
87
+ """
88
+ name: str
89
+ description: str
90
+ save_chat: bool = True
91
+ callbacks: Optional[AgentCallbacks] = None
92
+ # Optional: Flag to enable/disable agent debug trace logging
93
+ # If true, the agent will log additional debug information
94
+ LOG_AGENT_DEBUG_TRACE: Optional[bool] = False
95
+
96
+ class Agent(ABC):
97
+ """
98
+ Abstract base class for all agents in the system.
99
+
100
+ Implements common functionality and defines the required interface
101
+ for concrete agent implementations.
102
+ """
103
+
104
+ def __init__(self, options: AgentOptions):
105
+ """
106
+ Initialize a new agent with the given options.
107
+
108
+ Args:
109
+ options: Configuration options for this agent
110
+ """
111
+ self.name = options.name
112
+ self.id = self.generate_key_from_name(options.name)
113
+ self.description = options.description
114
+ self.save_chat = options.save_chat
115
+ self.callbacks = options.callbacks if options.callbacks is not None else AgentCallbacks()
116
+ self.log_debug_trace = options.LOG_AGENT_DEBUG_TRACE
117
+
118
+ def is_streaming_enabled(self) -> bool:
119
+ """
120
+ Whether this agent supports streaming responses.
121
+
122
+ Returns:
123
+ True if streaming is enabled, False otherwise
124
+ """
125
+ return False
126
+
127
+ @staticmethod
128
+ def generate_key_from_name(name: str) -> str:
129
+ """
130
+ Generate a standardized key from an agent name.
131
+
132
+ Args:
133
+ name: The display name to convert
134
+
135
+ Returns:
136
+ A lowercase, hyphenated key with special characters removed
137
+ """
138
+ # Remove special characters and replace spaces with hyphens
139
+ key = re.sub(r"[^a-zA-Z0-9\s-]", "", name)
140
+ key = re.sub(r"\s+", "-", key)
141
+ return key.lower()
142
+
143
+ @abstractmethod
144
+ async def process_request(
145
+ self,
146
+ input_text: str,
147
+ user_id: str,
148
+ session_id: str,
149
+ chat_history: list[ConversationMessage],
150
+ additional_params: Optional[AgentParamsType] = None,
151
+ ) -> Union[ConversationMessage, AsyncIterable[AgentOutputType]]:
152
+ """
153
+ Process a user request and generate a response.
154
+
155
+ Args:
156
+ input_text: The user's input text
157
+ user_id: Identifier for the user
158
+ session_id: Identifier for the current session
159
+ chat_history: List of previous messages in the conversation
160
+ additional_params: Optional additional parameters
161
+
162
+ Returns:
163
+ Either a complete message or an async iterable for streaming responses
164
+ """
165
+ pass
166
+
167
+ def log_debug(self, class_name: str, message: str, data: Any = None) -> None:
168
+ """
169
+ Log a debug message if debug tracing is enabled.
170
+
171
+ Args:
172
+ class_name: Name of the class logging the message
173
+ message: The message to log
174
+ data: Optional data to include in the log
175
+ """
176
+ if self.log_debug_trace:
177
+ prefix = f"> {class_name} \n> {self.name} \n>"
178
+ if data:
179
+ Logger.info(f"{prefix} {message} \n> {data}")
180
+ else:
181
+ Logger.info(f"{prefix} {message} \n>")
@@ -0,0 +1,172 @@
1
+ """
2
+ Amazon Bedrock Agent Integration Module
3
+
4
+ This module provides a robust implementation for interacting with Amazon Bedrock agents,
5
+ offering a flexible and extensible way to process conversational interactions using
6
+ AWS Bedrock's agent runtime capabilities.
7
+ """
8
+
9
+ from typing import Any, Optional
10
+ from dataclasses import dataclass
11
+ import os
12
+ import boto3
13
+ from botocore.exceptions import BotoCoreError, ClientError
14
+ from agent_squad.agents import Agent, AgentOptions, AgentStreamResponse
15
+ from agent_squad.types import ConversationMessage, ParticipantRole
16
+ from agent_squad.utils import Logger
17
+ from agent_squad.shared import user_agent
18
+
19
+
20
+ @dataclass
21
+ class AmazonBedrockAgentOptions(AgentOptions):
22
+ """
23
+ Configuration options for Amazon Bedrock Agent initialization.
24
+
25
+ Provides flexible configuration for Bedrock agent runtime:
26
+ - agent_id: Unique identifier for the Bedrock agent
27
+ - agent_alias_id: Specific alias for the agent
28
+ - client: Optional custom boto3 client (allows dependency injection)
29
+ - streaming: Flag to enable streaming response mode (on final response)
30
+ - enableTrace: Flag to enable detailed event tracing
31
+ """
32
+ region: Optional[str] = None
33
+ agent_id: str = None
34
+ agent_alias_id: str = None
35
+ client: Any | None = None
36
+ streaming: bool | None = False
37
+ enableTrace: bool | None = False
38
+
39
+
40
+ class AmazonBedrockAgent(Agent):
41
+ """
42
+ Specialized agent for interacting with Amazon Bedrock's intelligent agent runtime.
43
+
44
+ This class extends the base Agent class to provide:
45
+ - Direct integration with AWS Bedrock agent runtime
46
+ - Configurable response handling (streaming/non-streaming)
47
+ - Comprehensive error management
48
+ - Flexible session and conversation state management
49
+ """
50
+
51
+ def __init__(self, options: AmazonBedrockAgentOptions):
52
+ """
53
+ Initialize the Bedrock agent with comprehensive configuration.
54
+
55
+ Handles client creation, either using a provided client or
56
+ automatically creating one based on AWS configuration.
57
+
58
+ :param options: Detailed configuration for agent initialization
59
+ """
60
+ super().__init__(options)
61
+
62
+ # Store core agent identifiers
63
+ self.agent_id = options.agent_id
64
+ self.agent_alias_id = options.agent_alias_id
65
+
66
+ # Set up Bedrock runtime client
67
+ if options.client:
68
+ # Use provided client (useful for testing or custom configurations)
69
+ self.client = options.client
70
+ else:
71
+ # Create default client using AWS region from options or environment
72
+ self.client = boto3.client('bedrock-agent-runtime',
73
+ region_name=options.region or os.environ.get('AWS_REGION'))
74
+
75
+ user_agent.register_feature_to_client(self.client, feature="bedrock-agent")
76
+
77
+
78
+ # Configure response handling modes
79
+ self.streaming = options.streaming
80
+ self.enableTrace = options.enableTrace
81
+
82
+ def is_streaming_enabled(self) -> bool:
83
+ """
84
+ Check if streaming mode is active for response processing.
85
+
86
+ :return: Boolean indicating streaming status
87
+ """
88
+ return self.streaming is True
89
+
90
+ async def process_request(
91
+ self,
92
+ input_text: str,
93
+ user_id: str,
94
+ session_id: str,
95
+ chat_history: list[ConversationMessage],
96
+ additional_params: dict[str, str] | None = None
97
+ ) -> ConversationMessage:
98
+ """
99
+ Process a user request through the Bedrock agent runtime.
100
+
101
+ Handles the entire interaction lifecycle:
102
+ - Manages session state
103
+ - Invokes agent with configured parameters
104
+ - Processes streaming or non-streaming responses
105
+ - Handles potential errors
106
+
107
+ :param input_text: User's input message
108
+ :param user_id: Identifier for the user
109
+ :param session_id: Unique conversation session identifier
110
+ :param chat_history: Previous conversation messages
111
+ :param additional_params: Optional supplementary parameters
112
+ :return: Agent's response as a conversation message
113
+ """
114
+ # Initialize session state, defaulting to empty if not provided
115
+ session_state = {}
116
+ if (additional_params and 'sessionState' in additional_params):
117
+ session_state = additional_params['sessionState']
118
+
119
+ try:
120
+ # Configure streaming behavior
121
+ streamingConfigurations = {
122
+ 'streamFinalResponse': self.streaming
123
+ }
124
+
125
+ # Invoke Bedrock agent with comprehensive configuration
126
+ response = self.client.invoke_agent(
127
+ agentId=self.agent_id,
128
+ agentAliasId=self.agent_alias_id,
129
+ sessionId=session_id,
130
+ inputText=input_text,
131
+ enableTrace=self.enableTrace,
132
+ sessionState=session_state,
133
+ streamingConfigurations=streamingConfigurations if self.streaming else {}
134
+ )
135
+
136
+ completion = ""
137
+
138
+ if self.streaming:
139
+ async def generate_chunks():
140
+ nonlocal completion
141
+ for event in response['completion']:
142
+ if 'chunk' in event:
143
+ chunk = event['chunk']
144
+ decoded_response = chunk['bytes'].decode('utf-8')
145
+ self.callbacks.on_llm_new_token(decoded_response)
146
+ completion += decoded_response
147
+ yield AgentStreamResponse(text=decoded_response)
148
+ elif 'trace' in event and self.enableTrace:
149
+ Logger.info(f"Received event: {event}")
150
+ yield AgentStreamResponse(
151
+ final_message=ConversationMessage(
152
+ role=ParticipantRole.ASSISTANT.value,
153
+ content=[{'text':completion}]))
154
+ return generate_chunks()
155
+ else:
156
+ for event in response['completion']:
157
+ if 'chunk' in event:
158
+ chunk = event['chunk']
159
+ decoded_response = chunk['bytes'].decode('utf-8')
160
+ self.callbacks.on_llm_new_token(decoded_response)
161
+ completion += decoded_response
162
+ elif 'trace' in event and self.enableTrace:
163
+ Logger.info(f"Received event: {event}")
164
+
165
+ return ConversationMessage(
166
+ role=ParticipantRole.ASSISTANT.value,
167
+ content=[{"text": completion}]
168
+ )
169
+ except (BotoCoreError, ClientError) as error:
170
+ # Comprehensive error logging and propagation
171
+ Logger.error(f"Error processing request: {str(error)}")
172
+ raise error