aw_agents 0.1.2__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,55 @@
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.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
+ from aw_agents.util import AW_AGENTS_DATA_DIR, djoin
26
+
27
+ # Core abstractions
28
+ from aw_agents.base import AgentBase, ToolExecutionResult, create_json_schema
29
+
30
+ # Adapters
31
+ from aw_agents.adapters import (
32
+ MCPAdapter,
33
+ OpenAPIAdapter,
34
+ create_mcp_server_script,
35
+ create_api_server_script,
36
+ )
37
+
38
+ # Agents
39
+ from aw_agents.agents.download import DownloadAgent
40
+
41
+ __all__ = [
42
+ # Version
43
+ "__version__",
44
+ # Base
45
+ "AgentBase",
46
+ "ToolExecutionResult",
47
+ "create_json_schema",
48
+ # Adapters
49
+ "MCPAdapter",
50
+ "OpenAPIAdapter",
51
+ "create_mcp_server_script",
52
+ "create_api_server_script",
53
+ # Agents
54
+ "DownloadAgent",
55
+ ]
@@ -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,187 @@
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., 'agents.download' from 'aw_agents.agents.download.agent')
144
+ parts = agent_module.split(".")
145
+ if len(parts) > 3:
146
+ import_module = ".".join(parts[:3]) # aw_agents.agents.download
147
+ elif len(parts) > 2:
148
+ import_module = ".".join(parts[:2]) # aw_agents.agents
149
+ else:
150
+ import_module = agent_module
151
+ else:
152
+ import_module = agent_module
153
+
154
+ script_content = f'''"""
155
+ MCP Server for {agent_class.__name__}
156
+
157
+ Auto-generated MCP server script.
158
+
159
+ To use with Claude Desktop, add to your config:
160
+ {{
161
+ "mcpServers": {{
162
+ "{server_name}": {{
163
+ "command": "python",
164
+ "args": ["{output_path.absolute()}"]
165
+ }}
166
+ }}
167
+ }}
168
+ """
169
+
170
+ from aw_agents.adapters.mcp import MCPAdapter
171
+ from {import_module} import {agent_class.__name__}
172
+
173
+
174
+ def main():
175
+ agent = {agent_class.__name__}()
176
+ adapter = MCPAdapter(agent, "{server_name}")
177
+ adapter.run_sync()
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
182
+ '''
183
+
184
+ output_path.write_text(script_content)
185
+ output_path.chmod(0o755)
186
+
187
+ return output_path
@@ -0,0 +1,293 @@
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 __future__ import annotations
9
+
10
+ from typing import Any, Dict, Optional
11
+ from pathlib import Path
12
+
13
+ try:
14
+ from fastapi import FastAPI, HTTPException
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ from pydantic import BaseModel, Field, create_model
17
+ import uvicorn
18
+
19
+ FASTAPI_AVAILABLE = True
20
+ except ImportError:
21
+ FASTAPI_AVAILABLE = False
22
+ print(
23
+ "Warning: fastapi not installed. Install with: pip install fastapi uvicorn pydantic"
24
+ )
25
+
26
+ from aw_agents.base import AgentBase
27
+
28
+
29
+ class OpenAPIAdapter:
30
+ """
31
+ Adapter to expose an AgentBase as a FastAPI/OpenAPI service.
32
+
33
+ Usage:
34
+ agent = YourAgent()
35
+ adapter = OpenAPIAdapter(agent, title="Your Agent API")
36
+ adapter.run(port=8000)
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ agent: AgentBase,
42
+ *,
43
+ title: str = "AI Agent API",
44
+ description: str = "AI Agent exposed via OpenAPI",
45
+ version: str = "1.0.0",
46
+ server_url: Optional[str] = None,
47
+ ):
48
+ """
49
+ Initialize OpenAPI adapter.
50
+
51
+ Args:
52
+ agent: Agent instance to wrap
53
+ title: API title
54
+ description: API description
55
+ version: API version
56
+ server_url: Optional server URL for OpenAPI schema (e.g., for ngrok)
57
+ """
58
+ if not FASTAPI_AVAILABLE:
59
+ raise ImportError(
60
+ "fastapi required. Install with: pip install fastapi uvicorn pydantic"
61
+ )
62
+
63
+ self.agent = agent
64
+
65
+ # Get metadata from agent
66
+ metadata = agent.get_metadata()
67
+
68
+ self.app = FastAPI(
69
+ title=title or metadata.get("name", "AI Agent API"),
70
+ description=description
71
+ or metadata.get("description", "AI Agent exposed via OpenAPI"),
72
+ version=version or metadata.get("version", "1.0.0"),
73
+ )
74
+
75
+ # Add CORS middleware
76
+ self.app.add_middleware(
77
+ CORSMiddleware,
78
+ allow_origins=["*"], # Restrict in production
79
+ allow_credentials=True,
80
+ allow_methods=["*"],
81
+ allow_headers=["*"],
82
+ )
83
+
84
+ self.server_url = server_url
85
+ self._setup_routes()
86
+
87
+ def _setup_routes(self):
88
+ """Set up FastAPI routes from agent tools."""
89
+
90
+ # Root endpoint
91
+ @self.app.get("/")
92
+ async def root():
93
+ """Root endpoint with API information."""
94
+ metadata = self.agent.get_metadata()
95
+ return {
96
+ "name": metadata.get("name"),
97
+ "version": metadata.get("version"),
98
+ "description": metadata.get("description"),
99
+ "docs": "/docs",
100
+ "openapi": "/openapi.json",
101
+ }
102
+
103
+ # Health check
104
+ @self.app.get("/health")
105
+ async def health_check():
106
+ """Health check endpoint."""
107
+ return {"status": "healthy"}
108
+
109
+ # Create endpoints for each tool
110
+ for tool in self.agent.get_tools():
111
+ self._create_tool_endpoint(tool)
112
+
113
+ def _create_tool_endpoint(self, tool: Dict[str, Any]):
114
+ """Create a FastAPI endpoint for a tool."""
115
+ name = tool["name"]
116
+ description = tool["description"]
117
+ parameters = tool["parameters"]
118
+
119
+ # Create Pydantic model for request
120
+ request_model = self._create_pydantic_model(f"{name}_request", parameters)
121
+
122
+ # Create Pydantic model for response
123
+ response_model = create_model(
124
+ f"{name}_response",
125
+ success=(bool, Field(..., description="Whether operation succeeded")),
126
+ data=(Optional[Any], Field(None, description="Result data")),
127
+ message=(Optional[str], Field(None, description="Message")),
128
+ warnings=(Optional[list[str]], Field(None, description="Warnings")),
129
+ metadata=(Optional[Dict[str, Any]], Field(None, description="Metadata")),
130
+ )
131
+
132
+ # Create endpoint
133
+ @self.app.post(
134
+ f"/{name.replace('_', '-')}",
135
+ response_model=response_model,
136
+ description=description,
137
+ )
138
+ async def tool_endpoint(request: request_model): # type: ignore
139
+ try:
140
+ result = self.agent.execute_tool(name, request.dict())
141
+ return result
142
+ except Exception as e:
143
+ raise HTTPException(status_code=500, detail=str(e))
144
+
145
+ # Store endpoint reference (needed for FastAPI)
146
+ setattr(self, f"_endpoint_{name}", tool_endpoint)
147
+
148
+ def _create_pydantic_model(
149
+ self, model_name: str, json_schema: Dict[str, Any]
150
+ ) -> type[BaseModel]:
151
+ """Create a Pydantic model from JSON schema."""
152
+ properties = json_schema.get("properties", {})
153
+ required = set(json_schema.get("required", []))
154
+
155
+ fields = {}
156
+ for prop_name, prop_schema in properties.items():
157
+ prop_type = self._json_type_to_python(prop_schema.get("type", "string"))
158
+ prop_desc = prop_schema.get("description", "")
159
+
160
+ if prop_name in required:
161
+ fields[prop_name] = (prop_type, Field(..., description=prop_desc))
162
+ else:
163
+ fields[prop_name] = (
164
+ Optional[prop_type],
165
+ Field(None, description=prop_desc),
166
+ )
167
+
168
+ return create_model(model_name, **fields) # type: ignore
169
+
170
+ def _json_type_to_python(self, json_type: str) -> type:
171
+ """Convert JSON schema type to Python type."""
172
+ type_map = {
173
+ "string": str,
174
+ "integer": int,
175
+ "number": float,
176
+ "boolean": bool,
177
+ "array": list,
178
+ "object": dict,
179
+ }
180
+ return type_map.get(json_type, str)
181
+
182
+ def _customize_openapi_schema(self, host: str, port: int):
183
+ """Add servers field to OpenAPI schema."""
184
+ if self.app.openapi_schema:
185
+ return self.app.openapi_schema
186
+
187
+ # Use get_openapi to generate the schema (instead of calling self.app.openapi())
188
+ from fastapi.openapi.utils import get_openapi
189
+
190
+ openapi_schema = get_openapi(
191
+ title=self.app.title,
192
+ version=self.app.version,
193
+ description=self.app.description,
194
+ routes=self.app.routes,
195
+ )
196
+
197
+ # Use localhost instead of 0.0.0.0 for the schema URL
198
+ # 0.0.0.0 is a bind address, not a valid URL
199
+ if self.server_url:
200
+ server_url = self.server_url
201
+ else:
202
+ schema_host = "localhost" if host == "0.0.0.0" else host
203
+ server_url = f"http://{schema_host}:{port}"
204
+
205
+ openapi_schema["servers"] = [
206
+ {"url": server_url, "description": "Development server"}
207
+ ]
208
+
209
+ self.app.openapi_schema = openapi_schema
210
+ return openapi_schema
211
+
212
+ def run(self, host: str = "0.0.0.0", port: int = 8000, **kwargs):
213
+ """
214
+ Run the FastAPI server.
215
+
216
+ Args:
217
+ host: Host to bind to
218
+ port: Port to bind to
219
+ **kwargs: Additional uvicorn arguments
220
+ """
221
+ self.app.openapi = lambda: self._customize_openapi_schema(host, port)
222
+ uvicorn.run(self.app, host=host, port=port, **kwargs)
223
+
224
+
225
+ def create_api_server_script(
226
+ agent_class, output_path: Path, *, default_port: int = 8000
227
+ ):
228
+ """
229
+ Generate an API server script for an agent.
230
+
231
+ Args:
232
+ agent_class: Agent class to wrap
233
+ output_path: Path to write the script
234
+ default_port: Default port for the server
235
+ """
236
+ # Determine module path for import
237
+ agent_module = agent_class.__module__
238
+ if agent_module.startswith("aw_agents."):
239
+ # Extract the submodule (e.g., 'agents.download' from 'aw_agents.agents.download.agent')
240
+ parts = agent_module.split(".")
241
+ if len(parts) > 3:
242
+ import_module = ".".join(parts[:3]) # aw_agents.agents.download
243
+ elif len(parts) > 2:
244
+ import_module = ".".join(parts[:2]) # aw_agents.agents
245
+ else:
246
+ import_module = agent_module
247
+ else:
248
+ import_module = agent_module
249
+
250
+ script_content = f'''"""
251
+ FastAPI Server for {agent_class.__name__}
252
+
253
+ Auto-generated API server script.
254
+
255
+ To run:
256
+ python {output_path.name} [--port PORT]
257
+
258
+ To use with ChatGPT Custom GPT:
259
+ 1. Start this server
260
+ 2. Go to https://chat.openai.com/gpts/editor
261
+ 3. Create a Custom GPT
262
+ 4. Add action using schema from: http://localhost:{default_port}/openapi.json
263
+ """
264
+
265
+ import argparse
266
+ from aw_agents.adapters.openapi import OpenAPIAdapter
267
+ from {import_module} import {agent_class.__name__}
268
+
269
+
270
+ def main():
271
+ parser = argparse.ArgumentParser(description='Run {agent_class.__name__} API server')
272
+ parser.add_argument('--port', type=int, default={default_port}, help='Port to run on')
273
+ parser.add_argument('--host', type=str, default='0.0.0.0', help='Host to bind to')
274
+ args = parser.parse_args()
275
+
276
+ agent = {agent_class.__name__}()
277
+ adapter = OpenAPIAdapter(agent)
278
+
279
+ print(f"Starting {agent_class.__name__} API server...")
280
+ print(f" OpenAPI spec: http://localhost:{{args.port}}/openapi.json")
281
+ print(f" Docs: http://localhost:{{args.port}}/docs")
282
+
283
+ adapter.run(host=args.host, port=args.port)
284
+
285
+
286
+ if __name__ == "__main__":
287
+ main()
288
+ '''
289
+
290
+ output_path.write_text(script_content)
291
+ output_path.chmod(0o755)
292
+
293
+ return output_path
@@ -0,0 +1,9 @@
1
+ """
2
+ Agents for agentic workflows.
3
+
4
+ This module contains various AI agents that can be deployed to chatbot platforms.
5
+ """
6
+
7
+ from aw_agents.agents.download import DownloadAgent
8
+
9
+ __all__ = ["DownloadAgent"]
@@ -0,0 +1,6 @@
1
+ """Download Agent - Smart content downloader with context-aware naming."""
2
+
3
+ from aw_agents.agents.download.agent import DownloadAgent
4
+ from aw_agents.agents.download.download_core import DownloadEngine, download_content
5
+
6
+ __all__ = ["DownloadAgent", "DownloadEngine", "download_content"]