aw_agents 0.1.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.
aw_agents/__init__.py ADDED
@@ -0,0 +1,53 @@
1
+ """
2
+ aw_agents - AI Agents for Agentic Workflows
3
+
4
+ A collection of AI agents that can be easily deployed to multiple chatbot
5
+ platforms (Claude, ChatGPT, etc.) through adapters.
6
+
7
+ Agents:
8
+ - DownloadAgent: Smart content downloader with context-aware naming
9
+
10
+ Adapters:
11
+ - MCPAdapter: For Claude Desktop (MCP protocol)
12
+ - OpenAPIAdapter: For ChatGPT Custom GPTs (OpenAPI/FastAPI)
13
+
14
+ Example:
15
+ >>> from aw_agents.download import DownloadAgent
16
+ >>> from aw_agents.adapters import MCPAdapter
17
+ >>>
18
+ >>> agent = DownloadAgent()
19
+ >>> adapter = MCPAdapter(agent, "download-agent")
20
+ >>> adapter.run() # Serves agent via MCP for Claude
21
+ """
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ # Core abstractions
26
+ from aw_agents.base import AgentBase, ToolExecutionResult, create_json_schema
27
+
28
+ # Adapters
29
+ from aw_agents.adapters import (
30
+ MCPAdapter,
31
+ OpenAPIAdapter,
32
+ create_mcp_server_script,
33
+ create_api_server_script,
34
+ )
35
+
36
+ # Agents
37
+ from aw_agents.download import DownloadAgent
38
+
39
+ __all__ = [
40
+ # Version
41
+ '__version__',
42
+ # Base
43
+ 'AgentBase',
44
+ 'ToolExecutionResult',
45
+ 'create_json_schema',
46
+ # Adapters
47
+ 'MCPAdapter',
48
+ 'OpenAPIAdapter',
49
+ 'create_mcp_server_script',
50
+ 'create_api_server_script',
51
+ # Agents
52
+ 'DownloadAgent',
53
+ ]
@@ -0,0 +1,11 @@
1
+ """Adapters for exposing agents to different platforms."""
2
+
3
+ from aw_agents.adapters.mcp import MCPAdapter, create_mcp_server_script
4
+ from aw_agents.adapters.openapi import OpenAPIAdapter, create_api_server_script
5
+
6
+ __all__ = [
7
+ 'MCPAdapter',
8
+ 'OpenAPIAdapter',
9
+ 'create_mcp_server_script',
10
+ 'create_api_server_script',
11
+ ]
@@ -0,0 +1,185 @@
1
+ """
2
+ MCP (Model Context Protocol) adapter for AW agents.
3
+
4
+ This adapter wraps any AgentBase subclass to expose it as an MCP server
5
+ for use with Claude Desktop.
6
+ """
7
+
8
+ import asyncio
9
+ from typing import Any, Dict
10
+ from pathlib import Path
11
+
12
+ try:
13
+ from mcp.server import Server
14
+ from mcp.server.stdio import stdio_server
15
+ from mcp.types import Tool, TextContent
16
+
17
+ MCP_AVAILABLE = True
18
+ except ImportError:
19
+ MCP_AVAILABLE = False
20
+ print("Warning: mcp package not installed. Install with: pip install mcp")
21
+
22
+ from aw_agents.base import AgentBase
23
+
24
+
25
+ class MCPAdapter:
26
+ """
27
+ Adapter to expose an AgentBase as an MCP server.
28
+
29
+ Usage:
30
+ agent = YourAgent()
31
+ adapter = MCPAdapter(agent, server_name="your-agent")
32
+ adapter.run()
33
+ """
34
+
35
+ def __init__(self, agent: AgentBase, server_name: str):
36
+ """
37
+ Initialize MCP adapter.
38
+
39
+ Args:
40
+ agent: Agent instance to wrap
41
+ server_name: Name for the MCP server
42
+ """
43
+ if not MCP_AVAILABLE:
44
+ raise ImportError("mcp package required. Install with: pip install mcp")
45
+
46
+ self.agent = agent
47
+ self.server = Server(server_name)
48
+ self._setup_handlers()
49
+
50
+ def _setup_handlers(self):
51
+ """Set up MCP server handlers."""
52
+
53
+ @self.server.list_tools()
54
+ async def list_tools() -> list[Tool]:
55
+ """List available tools from the agent."""
56
+ agent_tools = self.agent.get_tools()
57
+
58
+ mcp_tools = []
59
+ for tool in agent_tools:
60
+ mcp_tools.append(
61
+ Tool(
62
+ name=tool['name'],
63
+ description=tool['description'],
64
+ inputSchema=tool['parameters'],
65
+ )
66
+ )
67
+
68
+ return mcp_tools
69
+
70
+ @self.server.call_tool()
71
+ async def call_tool(name: str, arguments: dict) -> list[TextContent]:
72
+ """Handle tool calls from Claude."""
73
+ try:
74
+ result = self.agent.execute_tool(name, arguments)
75
+
76
+ # Format response based on result
77
+ if result['success']:
78
+ response_text = self._format_success_response(result)
79
+ else:
80
+ response_text = self._format_error_response(result)
81
+
82
+ return [TextContent(type="text", text=response_text)]
83
+
84
+ except Exception as e:
85
+ return [
86
+ TextContent(
87
+ type="text", text=f"❌ Error executing {name}:\n{str(e)}"
88
+ )
89
+ ]
90
+
91
+ def _format_success_response(self, result: Dict[str, Any]) -> str:
92
+ """Format a successful tool execution response."""
93
+ parts = []
94
+
95
+ if result.get('message'):
96
+ parts.append(f"✓ {result['message']}")
97
+ else:
98
+ parts.append("✓ Operation completed successfully")
99
+
100
+ # Add data if present
101
+ if result.get('data'):
102
+ parts.append("")
103
+ parts.append(str(result['data']))
104
+
105
+ # Add warnings if present
106
+ if result.get('warnings'):
107
+ parts.append("")
108
+ parts.append("Warnings:")
109
+ for warning in result['warnings']:
110
+ parts.append(f" • {warning}")
111
+
112
+ return "\n".join(parts)
113
+
114
+ def _format_error_response(self, result: Dict[str, Any]) -> str:
115
+ """Format an error response."""
116
+ message = result.get('message', 'Unknown error')
117
+ return f"❌ Error: {message}"
118
+
119
+ async def run(self):
120
+ """Run the MCP server."""
121
+ async with stdio_server() as (read_stream, write_stream):
122
+ await self.server.run(
123
+ read_stream, write_stream, self.server.create_initialization_options()
124
+ )
125
+
126
+ def run_sync(self):
127
+ """Run the MCP server (synchronous wrapper)."""
128
+ asyncio.run(self.run())
129
+
130
+
131
+ def create_mcp_server_script(agent_class, server_name: str, output_path: Path):
132
+ """
133
+ Generate an MCP server script for an agent.
134
+
135
+ Args:
136
+ agent_class: Agent class to wrap
137
+ server_name: Name for the MCP server
138
+ output_path: Path to write the script
139
+ """
140
+ # Determine module path for import
141
+ agent_module = agent_class.__module__
142
+ if agent_module.startswith('aw_agents.'):
143
+ # Extract the submodule (e.g., 'download' from 'aw_agents.download.agent')
144
+ parts = agent_module.split('.')
145
+ if len(parts) > 2:
146
+ import_module = '.'.join(parts[:2]) # aw_agents.download
147
+ else:
148
+ import_module = agent_module
149
+ else:
150
+ import_module = agent_module
151
+
152
+ script_content = f'''"""
153
+ MCP Server for {agent_class.__name__}
154
+
155
+ Auto-generated MCP server script.
156
+
157
+ To use with Claude Desktop, add to your config:
158
+ {{
159
+ "mcpServers": {{
160
+ "{server_name}": {{
161
+ "command": "python",
162
+ "args": ["{output_path.absolute()}"]
163
+ }}
164
+ }}
165
+ }}
166
+ """
167
+
168
+ from aw_agents.adapters.mcp import MCPAdapter
169
+ from {import_module} import {agent_class.__name__}
170
+
171
+
172
+ def main():
173
+ agent = {agent_class.__name__}()
174
+ adapter = MCPAdapter(agent, "{server_name}")
175
+ adapter.run_sync()
176
+
177
+
178
+ if __name__ == "__main__":
179
+ main()
180
+ '''
181
+
182
+ output_path.write_text(script_content)
183
+ output_path.chmod(0o755)
184
+
185
+ return output_path
@@ -0,0 +1,255 @@
1
+ """
2
+ OpenAPI/FastAPI adapter for AW agents.
3
+
4
+ This adapter wraps any AgentBase subclass to expose it as a REST API
5
+ with OpenAPI spec for use with ChatGPT Custom GPTs.
6
+ """
7
+
8
+ from typing import Any, Dict, Optional
9
+ from pathlib import Path
10
+
11
+ try:
12
+ from fastapi import FastAPI, HTTPException
13
+ from fastapi.middleware.cors import CORSMiddleware
14
+ from pydantic import BaseModel, Field, create_model
15
+ import uvicorn
16
+
17
+ FASTAPI_AVAILABLE = True
18
+ except ImportError:
19
+ FASTAPI_AVAILABLE = False
20
+ print(
21
+ "Warning: fastapi not installed. Install with: pip install fastapi uvicorn pydantic"
22
+ )
23
+
24
+ from aw_agents.base import AgentBase
25
+
26
+
27
+ class OpenAPIAdapter:
28
+ """
29
+ Adapter to expose an AgentBase as a FastAPI/OpenAPI service.
30
+
31
+ Usage:
32
+ agent = YourAgent()
33
+ adapter = OpenAPIAdapter(agent, title="Your Agent API")
34
+ adapter.run(port=8000)
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ agent: AgentBase,
40
+ *,
41
+ title: str = "AI Agent API",
42
+ description: str = "AI Agent exposed via OpenAPI",
43
+ version: str = "1.0.0",
44
+ ):
45
+ """
46
+ Initialize OpenAPI adapter.
47
+
48
+ Args:
49
+ agent: Agent instance to wrap
50
+ title: API title
51
+ description: API description
52
+ version: API version
53
+ """
54
+ if not FASTAPI_AVAILABLE:
55
+ raise ImportError(
56
+ "fastapi required. Install with: pip install fastapi uvicorn pydantic"
57
+ )
58
+
59
+ self.agent = agent
60
+
61
+ # Get metadata from agent
62
+ metadata = agent.get_metadata()
63
+
64
+ self.app = FastAPI(
65
+ title=title or metadata.get('name', 'AI Agent API'),
66
+ description=description
67
+ or metadata.get('description', 'AI Agent exposed via OpenAPI'),
68
+ version=version or metadata.get('version', '1.0.0'),
69
+ )
70
+
71
+ # Add CORS middleware
72
+ self.app.add_middleware(
73
+ CORSMiddleware,
74
+ allow_origins=["*"], # Restrict in production
75
+ allow_credentials=True,
76
+ allow_methods=["*"],
77
+ allow_headers=["*"],
78
+ )
79
+
80
+ self._setup_routes()
81
+
82
+ def _setup_routes(self):
83
+ """Set up FastAPI routes from agent tools."""
84
+
85
+ # Root endpoint
86
+ @self.app.get("/")
87
+ async def root():
88
+ """Root endpoint with API information."""
89
+ metadata = self.agent.get_metadata()
90
+ return {
91
+ "name": metadata.get('name'),
92
+ "version": metadata.get('version'),
93
+ "description": metadata.get('description'),
94
+ "docs": "/docs",
95
+ "openapi": "/openapi.json",
96
+ }
97
+
98
+ # Health check
99
+ @self.app.get("/health")
100
+ async def health_check():
101
+ """Health check endpoint."""
102
+ return {"status": "healthy"}
103
+
104
+ # Create endpoints for each tool
105
+ for tool in self.agent.get_tools():
106
+ self._create_tool_endpoint(tool)
107
+
108
+ def _create_tool_endpoint(self, tool: Dict[str, Any]):
109
+ """Create a FastAPI endpoint for a tool."""
110
+ name = tool['name']
111
+ description = tool['description']
112
+ parameters = tool['parameters']
113
+
114
+ # Create Pydantic model for request
115
+ request_model = self._create_pydantic_model(f"{name}_request", parameters)
116
+
117
+ # Create Pydantic model for response
118
+ response_model = create_model(
119
+ f"{name}_response",
120
+ success=(bool, Field(..., description="Whether operation succeeded")),
121
+ data=(Optional[Any], Field(None, description="Result data")),
122
+ message=(Optional[str], Field(None, description="Message")),
123
+ warnings=(Optional[list[str]], Field(None, description="Warnings")),
124
+ metadata=(Optional[Dict[str, Any]], Field(None, description="Metadata")),
125
+ )
126
+
127
+ # Create endpoint
128
+ @self.app.post(
129
+ f"/{name.replace('_', '-')}",
130
+ response_model=response_model,
131
+ description=description,
132
+ )
133
+ async def tool_endpoint(request: request_model): # type: ignore
134
+ try:
135
+ result = self.agent.execute_tool(name, request.dict())
136
+ return result
137
+ except Exception as e:
138
+ raise HTTPException(status_code=500, detail=str(e))
139
+
140
+ # Store endpoint reference (needed for FastAPI)
141
+ setattr(self, f"_endpoint_{name}", tool_endpoint)
142
+
143
+ def _create_pydantic_model(
144
+ self, model_name: str, json_schema: Dict[str, Any]
145
+ ) -> type[BaseModel]:
146
+ """Create a Pydantic model from JSON schema."""
147
+ properties = json_schema.get('properties', {})
148
+ required = set(json_schema.get('required', []))
149
+
150
+ fields = {}
151
+ for prop_name, prop_schema in properties.items():
152
+ prop_type = self._json_type_to_python(prop_schema.get('type', 'string'))
153
+ prop_desc = prop_schema.get('description', '')
154
+
155
+ if prop_name in required:
156
+ fields[prop_name] = (prop_type, Field(..., description=prop_desc))
157
+ else:
158
+ fields[prop_name] = (
159
+ Optional[prop_type],
160
+ Field(None, description=prop_desc),
161
+ )
162
+
163
+ return create_model(model_name, **fields) # type: ignore
164
+
165
+ def _json_type_to_python(self, json_type: str) -> type:
166
+ """Convert JSON schema type to Python type."""
167
+ type_map = {
168
+ 'string': str,
169
+ 'integer': int,
170
+ 'number': float,
171
+ 'boolean': bool,
172
+ 'array': list,
173
+ 'object': dict,
174
+ }
175
+ return type_map.get(json_type, str)
176
+
177
+ def run(self, host: str = "0.0.0.0", port: int = 8000, **kwargs):
178
+ """
179
+ Run the FastAPI server.
180
+
181
+ Args:
182
+ host: Host to bind to
183
+ port: Port to bind to
184
+ **kwargs: Additional uvicorn arguments
185
+ """
186
+ uvicorn.run(self.app, host=host, port=port, **kwargs)
187
+
188
+
189
+ def create_api_server_script(
190
+ agent_class, output_path: Path, *, default_port: int = 8000
191
+ ):
192
+ """
193
+ Generate an API server script for an agent.
194
+
195
+ Args:
196
+ agent_class: Agent class to wrap
197
+ output_path: Path to write the script
198
+ default_port: Default port for the server
199
+ """
200
+ # Determine module path for import
201
+ agent_module = agent_class.__module__
202
+ if agent_module.startswith('aw_agents.'):
203
+ # Extract the submodule (e.g., 'download' from 'aw_agents.download.agent')
204
+ parts = agent_module.split('.')
205
+ if len(parts) > 2:
206
+ import_module = '.'.join(parts[:2]) # aw_agents.download
207
+ else:
208
+ import_module = agent_module
209
+ else:
210
+ import_module = agent_module
211
+
212
+ script_content = f'''"""
213
+ FastAPI Server for {agent_class.__name__}
214
+
215
+ Auto-generated API server script.
216
+
217
+ To run:
218
+ python {output_path.name} [--port PORT]
219
+
220
+ To use with ChatGPT Custom GPT:
221
+ 1. Start this server
222
+ 2. Go to https://chat.openai.com/gpts/editor
223
+ 3. Create a Custom GPT
224
+ 4. Add action using schema from: http://localhost:{default_port}/openapi.json
225
+ """
226
+
227
+ import argparse
228
+ from aw_agents.adapters.openapi import OpenAPIAdapter
229
+ from {import_module} import {agent_class.__name__}
230
+
231
+
232
+ def main():
233
+ parser = argparse.ArgumentParser(description='Run {agent_class.__name__} API server')
234
+ parser.add_argument('--port', type=int, default={default_port}, help='Port to run on')
235
+ parser.add_argument('--host', type=str, default='0.0.0.0', help='Host to bind to')
236
+ args = parser.parse_args()
237
+
238
+ agent = {agent_class.__name__}()
239
+ adapter = OpenAPIAdapter(agent)
240
+
241
+ print(f"Starting {agent_class.__name__} API server...")
242
+ print(f" OpenAPI spec: http://localhost:{{args.port}}/openapi.json")
243
+ print(f" Docs: http://localhost:{{args.port}}/docs")
244
+
245
+ adapter.run(host=args.host, port=args.port)
246
+
247
+
248
+ if __name__ == "__main__":
249
+ main()
250
+ '''
251
+
252
+ output_path.write_text(script_content)
253
+ output_path.chmod(0o755)
254
+
255
+ return output_path
aw_agents/base.py ADDED
@@ -0,0 +1,140 @@
1
+ """
2
+ Base classes and protocols for AW agents.
3
+
4
+ This module provides the foundation for building AI agents that can be
5
+ deployed to multiple chatbot platforms (Claude, ChatGPT, etc.).
6
+ """
7
+
8
+ from typing import Protocol, Any, Dict, Optional
9
+ from abc import ABC, abstractmethod
10
+
11
+
12
+ class AgentBase(ABC):
13
+ """
14
+ Base class for all AW agents.
15
+
16
+ Agents should inherit from this and implement the core methods.
17
+ Adapters (MCP, OpenAPI) will wrap these agents for deployment.
18
+ """
19
+
20
+ @abstractmethod
21
+ def get_tools(self) -> list[Dict[str, Any]]:
22
+ """
23
+ Return tool definitions for this agent.
24
+
25
+ Each tool should have:
26
+ - name: str
27
+ - description: str
28
+ - parameters: dict (JSON schema)
29
+
30
+ Returns:
31
+ List of tool definitions
32
+ """
33
+ pass
34
+
35
+ @abstractmethod
36
+ def execute_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
37
+ """
38
+ Execute a tool with given arguments.
39
+
40
+ Args:
41
+ name: Tool name
42
+ arguments: Tool arguments
43
+
44
+ Returns:
45
+ Result dictionary with at least:
46
+ - success: bool
47
+ - data: Any
48
+ - message: Optional[str]
49
+ - warnings: Optional[list[str]]
50
+ """
51
+ pass
52
+
53
+ def get_metadata(self) -> Dict[str, Any]:
54
+ """
55
+ Get agent metadata.
56
+
57
+ Returns:
58
+ Metadata including name, version, description
59
+ """
60
+ return {
61
+ 'name': self.__class__.__name__,
62
+ 'version': '1.0.0',
63
+ 'description': self.__doc__ or 'No description'
64
+ }
65
+
66
+
67
+ class ToolExecutionResult:
68
+ """Standard result format for tool execution."""
69
+
70
+ def __init__(
71
+ self,
72
+ success: bool,
73
+ data: Any = None,
74
+ message: Optional[str] = None,
75
+ warnings: Optional[list[str]] = None,
76
+ metadata: Optional[Dict[str, Any]] = None
77
+ ):
78
+ self.success = success
79
+ self.data = data
80
+ self.message = message
81
+ self.warnings = warnings or []
82
+ self.metadata = metadata or {}
83
+
84
+ def to_dict(self) -> Dict[str, Any]:
85
+ """Convert to dictionary format."""
86
+ return {
87
+ 'success': self.success,
88
+ 'data': self.data,
89
+ 'message': self.message,
90
+ 'warnings': self.warnings,
91
+ 'metadata': self.metadata
92
+ }
93
+
94
+ @classmethod
95
+ def success_result(
96
+ cls,
97
+ data: Any,
98
+ message: Optional[str] = None,
99
+ **kwargs
100
+ ) -> 'ToolExecutionResult':
101
+ """Create a success result."""
102
+ return cls(success=True, data=data, message=message, **kwargs)
103
+
104
+ @classmethod
105
+ def error_result(
106
+ cls,
107
+ message: str,
108
+ data: Any = None,
109
+ **kwargs
110
+ ) -> 'ToolExecutionResult':
111
+ """Create an error result."""
112
+ return cls(success=False, data=data, message=message, **kwargs)
113
+
114
+
115
+ def create_json_schema(
116
+ properties: Dict[str, Dict[str, Any]],
117
+ required: Optional[list[str]] = None,
118
+ **kwargs
119
+ ) -> Dict[str, Any]:
120
+ """
121
+ Helper to create JSON schema for tool parameters.
122
+
123
+ >>> schema = create_json_schema(
124
+ ... properties={
125
+ ... 'url': {'type': 'string', 'description': 'URL to process'},
126
+ ... 'context': {'type': 'string', 'description': 'Context info'}
127
+ ... },
128
+ ... required=['url']
129
+ ... )
130
+ >>> schema['type']
131
+ 'object'
132
+ >>> 'url' in schema['required']
133
+ True
134
+ """
135
+ return {
136
+ 'type': 'object',
137
+ 'properties': properties,
138
+ 'required': required or [],
139
+ **kwargs
140
+ }
@@ -0,0 +1,6 @@
1
+ """Download Agent - Smart content downloader with context-aware naming."""
2
+
3
+ from aw_agents.download.agent import DownloadAgent
4
+ from aw_agents.download.download_core import DownloadEngine, download_content
5
+
6
+ __all__ = ['DownloadAgent', 'DownloadEngine', 'download_content']