agent-weave-lib 0.1.0__tar.gz

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 (32) hide show
  1. agent_weave_lib-0.1.0/.gitignore +17 -0
  2. agent_weave_lib-0.1.0/LICENSE +21 -0
  3. agent_weave_lib-0.1.0/PKG-INFO +296 -0
  4. agent_weave_lib-0.1.0/README.md +254 -0
  5. agent_weave_lib-0.1.0/examples/custom_tools.py +86 -0
  6. agent_weave_lib-0.1.0/examples/multi_agent.py +63 -0
  7. agent_weave_lib-0.1.0/examples/quickstart.py +64 -0
  8. agent_weave_lib-0.1.0/pyproject.toml +74 -0
  9. agent_weave_lib-0.1.0/src/agent_weave/__init__.py +63 -0
  10. agent_weave_lib-0.1.0/src/agent_weave/agent.py +177 -0
  11. agent_weave_lib-0.1.0/src/agent_weave/cli.py +109 -0
  12. agent_weave_lib-0.1.0/src/agent_weave/config.py +51 -0
  13. agent_weave_lib-0.1.0/src/agent_weave/errors.py +64 -0
  14. agent_weave_lib-0.1.0/src/agent_weave/guardrails.py +144 -0
  15. agent_weave_lib-0.1.0/src/agent_weave/llm/__init__.py +5 -0
  16. agent_weave_lib-0.1.0/src/agent_weave/llm/anthropic_backend.py +174 -0
  17. agent_weave_lib-0.1.0/src/agent_weave/llm/base.py +43 -0
  18. agent_weave_lib-0.1.0/src/agent_weave/llm/openai_backend.py +153 -0
  19. agent_weave_lib-0.1.0/src/agent_weave/memory/__init__.py +10 -0
  20. agent_weave_lib-0.1.0/src/agent_weave/memory/base.py +53 -0
  21. agent_weave_lib-0.1.0/src/agent_weave/memory/conversation.py +84 -0
  22. agent_weave_lib-0.1.0/src/agent_weave/models.py +140 -0
  23. agent_weave_lib-0.1.0/src/agent_weave/py.typed +0 -0
  24. agent_weave_lib-0.1.0/src/agent_weave/react.py +309 -0
  25. agent_weave_lib-0.1.0/src/agent_weave/team.py +247 -0
  26. agent_weave_lib-0.1.0/src/agent_weave/tool.py +152 -0
  27. agent_weave_lib-0.1.0/tests/test_agent.py +149 -0
  28. agent_weave_lib-0.1.0/tests/test_guardrails.py +133 -0
  29. agent_weave_lib-0.1.0/tests/test_memory.py +96 -0
  30. agent_weave_lib-0.1.0/tests/test_react.py +196 -0
  31. agent_weave_lib-0.1.0/tests/test_team.py +101 -0
  32. agent_weave_lib-0.1.0/tests/test_tool.py +128 -0
@@ -0,0 +1,17 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.egg
9
+ .venv/
10
+ venv/
11
+ .env
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+ *.so
16
+ .coverage
17
+ htmlcov/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Soham Dahivalkar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,296 @@
1
+ Metadata-Version: 2.4
2
+ Name: agent-weave-lib
3
+ Version: 0.1.0
4
+ Summary: Lightweight AI agent framework with tool use, ReAct reasoning, multi-agent teams, and memory.
5
+ Project-URL: Homepage, https://github.com/sohammmmm10/agent-weave
6
+ Project-URL: Repository, https://github.com/sohammmmm10/agent-weave
7
+ Project-URL: Issues, https://github.com/sohammmmm10/agent-weave/issues
8
+ Author: Soham Dahivalkar
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: agent,ai,framework,llm,multi-agent,react,tool-use
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: typing-extensions>=4.8; python_version < '3.11'
25
+ Provides-Extra: all
26
+ Requires-Dist: ai-bridge-kit>=0.1.0; extra == 'all'
27
+ Requires-Dist: anthropic>=0.34.0; extra == 'all'
28
+ Requires-Dist: openai>=1.56.0; extra == 'all'
29
+ Provides-Extra: anthropic
30
+ Requires-Dist: anthropic>=0.34.0; extra == 'anthropic'
31
+ Provides-Extra: bridge
32
+ Requires-Dist: ai-bridge-kit>=0.1.0; extra == 'bridge'
33
+ Provides-Extra: dev
34
+ Requires-Dist: build>=1.2.2; extra == 'dev'
35
+ Requires-Dist: pytest-asyncio>=0.24.0; extra == 'dev'
36
+ Requires-Dist: pytest-cov>=5.0.0; extra == 'dev'
37
+ Requires-Dist: pytest>=8.0.0; extra == 'dev'
38
+ Requires-Dist: twine>=5.1.1; extra == 'dev'
39
+ Provides-Extra: openai
40
+ Requires-Dist: openai>=1.56.0; extra == 'openai'
41
+ Description-Content-Type: text/markdown
42
+
43
+ # agent-weave
44
+
45
+ `agent-weave` is a lightweight Python framework for building AI agents with tool use, ReAct reasoning, multi-agent teams, memory, and guardrails.
46
+
47
+ No bloat. No magic. Just clean, composable building blocks.
48
+
49
+ ## Features
50
+
51
+ - **`@tool` decorator** — Turn any Python function into an agent tool with auto-generated schemas.
52
+ - **ReAct loop** — Built-in Reasoning + Acting engine with configurable iteration limits.
53
+ - **Multi-agent teams** — Sequential pipelines, round-robin, and router-based orchestration.
54
+ - **Memory** — Conversation memory and sliding-window memory with system prompt preservation.
55
+ - **Guardrails** — PII detection, blocked words, regex filters, token budgets, and max-length checks.
56
+ - **Provider backends** — OpenAI, Anthropic, and any OpenAI-compatible API.
57
+ - **Async-first** — Full `async/await` support for every operation.
58
+ - **CLI** — Run agents and chat from the terminal.
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install -e .
64
+ ```
65
+
66
+ With OpenAI support:
67
+
68
+ ```bash
69
+ pip install -e ".[openai]"
70
+ ```
71
+
72
+ With Anthropic support:
73
+
74
+ ```bash
75
+ pip install -e ".[anthropic]"
76
+ ```
77
+
78
+ Install everything:
79
+
80
+ ```bash
81
+ pip install -e ".[all]"
82
+ ```
83
+
84
+ For development:
85
+
86
+ ```bash
87
+ pip install -e ".[dev,all]"
88
+ ```
89
+
90
+ ## Quick Start
91
+
92
+ ```python
93
+ import os
94
+ from agent_weave import Agent, tool
95
+ from agent_weave.llm.openai_backend import OpenAIBackend
96
+
97
+ @tool(description="Get the weather for a city")
98
+ def get_weather(city: str) -> str:
99
+ return f"72°F and sunny in {city}"
100
+
101
+ @tool(description="Calculate a math expression")
102
+ def calculator(expression: str) -> str:
103
+ return str(eval(expression))
104
+
105
+ agent = Agent(
106
+ name="assistant",
107
+ llm=OpenAIBackend(api_key=os.environ["OPENAI_API_KEY"]),
108
+ tools=[get_weather, calculator],
109
+ system_prompt="You are a helpful assistant. Use tools when needed.",
110
+ )
111
+
112
+ result = agent.run("What's the weather in NYC and what is 42 * 17?")
113
+ print(result.output)
114
+ print(f"Steps: {result.total_iterations}, Tokens: {result.total_tokens:,}")
115
+ ```
116
+
117
+ ## The `@tool` Decorator
118
+
119
+ Turn any function into a tool. Schemas are auto-generated from type hints:
120
+
121
+ ```python
122
+ from agent_weave import tool
123
+
124
+ @tool(description="Search the web for a query")
125
+ def web_search(query: str, max_results: int = 5) -> str:
126
+ return f"Results for: {query} (limit {max_results})"
127
+
128
+ # Access the generated schema
129
+ print(web_search.schema.to_openai_tool())
130
+ ```
131
+
132
+ ## Multi-Agent Teams
133
+
134
+ Chain agents in a pipeline, round-robin, or route to specialists:
135
+
136
+ ```python
137
+ from agent_weave import Agent, Team, Strategy
138
+ from agent_weave.llm.openai_backend import OpenAIBackend
139
+
140
+ backend = OpenAIBackend(api_key=os.environ["OPENAI_API_KEY"])
141
+
142
+ researcher = Agent(name="researcher", llm=backend,
143
+ system_prompt="Research the topic. Provide key facts.")
144
+
145
+ writer = Agent(name="writer", llm=backend,
146
+ system_prompt="Write a blog post from the research provided.")
147
+
148
+ editor = Agent(name="editor", llm=backend,
149
+ system_prompt="Polish and improve the writing.")
150
+
151
+ # Sequential: researcher -> writer -> editor
152
+ team = Team(
153
+ agents=[researcher, writer, editor],
154
+ strategy=Strategy.SEQUENTIAL,
155
+ )
156
+ result = team.run("AI agents in 2025")
157
+ print(result.final_output)
158
+ ```
159
+
160
+ ### Router Strategy
161
+
162
+ ```python
163
+ router = Agent(name="router", llm=backend,
164
+ system_prompt="You route tasks to the right specialist.")
165
+
166
+ team = Team(
167
+ agents=[researcher, writer],
168
+ strategy=Strategy.ROUTER,
169
+ router=router,
170
+ )
171
+ result = team.run("Write a poem about AI")
172
+ ```
173
+
174
+ ## Memory
175
+
176
+ ```python
177
+ from agent_weave.memory import ConversationMemory, SlidingWindowMemory
178
+
179
+ # Unlimited memory
180
+ agent = Agent(name="bot", llm=backend, memory=ConversationMemory())
181
+
182
+ # Fixed window (keeps last 20 messages + system prompt)
183
+ agent = Agent(name="bot", llm=backend,
184
+ memory=SlidingWindowMemory(max_messages=20))
185
+ ```
186
+
187
+ ## Guardrails
188
+
189
+ ```python
190
+ from agent_weave import (
191
+ Agent, MaxLengthGuardrail, PIIGuardrail, BlockedWordsGuardrail,
192
+ )
193
+
194
+ agent = Agent(
195
+ name="safe-bot",
196
+ llm=backend,
197
+ token_budget=10_000, # Max 10k tokens per run
198
+ output_guardrails=[
199
+ MaxLengthGuardrail(max_chars=5_000),
200
+ PIIGuardrail(redact=True),
201
+ BlockedWordsGuardrail(words=["confidential", "password"]),
202
+ ],
203
+ )
204
+ ```
205
+
206
+ ## Conversational Chat
207
+
208
+ ```python
209
+ agent = Agent(name="chatbot", llm=backend,
210
+ system_prompt="You are a friendly chatbot.")
211
+
212
+ # chat() preserves history across calls
213
+ agent.chat("Hello!")
214
+ agent.chat("What did I just say?") # Agent remembers
215
+ agent.reset() # Clear conversation
216
+ ```
217
+
218
+ ## Async Support
219
+
220
+ ```python
221
+ import asyncio
222
+
223
+ async def main():
224
+ result = await agent.arun("Summarize AI trends")
225
+ print(result.output)
226
+
227
+ asyncio.run(main())
228
+ ```
229
+
230
+ ## Anthropic Backend
231
+
232
+ ```python
233
+ from agent_weave.llm.anthropic_backend import AnthropicBackend
234
+
235
+ agent = Agent(
236
+ name="claude-agent",
237
+ llm=AnthropicBackend(api_key=os.environ["ANTHROPIC_API_KEY"]),
238
+ system_prompt="You are helpful.",
239
+ )
240
+ result = agent.run("Explain quantum computing simply.")
241
+ ```
242
+
243
+ ## CLI
244
+
245
+ ```bash
246
+ # Set your API key
247
+ export OPENAI_API_KEY="sk-..."
248
+
249
+ # Run a single task
250
+ agent-weave run "What are the top 3 AI trends in 2025?"
251
+
252
+ # Interactive chat
253
+ agent-weave chat
254
+
255
+ # Library info
256
+ agent-weave info
257
+ ```
258
+
259
+ ## Run Tests
260
+
261
+ ```bash
262
+ pip install -e ".[dev]"
263
+ python -m pytest
264
+ ```
265
+
266
+ ## Project Structure
267
+
268
+ ```
269
+ agent-weave/
270
+ ├── src/agent_weave/
271
+ │ ├── __init__.py # Public API
272
+ │ ├── agent.py # Core Agent class
273
+ │ ├── tool.py # @tool decorator & Tool class
274
+ │ ├── react.py # ReAct reasoning engine
275
+ │ ├── team.py # Multi-agent orchestration
276
+ │ ├── guardrails.py # Safety & validation
277
+ │ ├── config.py # Settings
278
+ │ ├── models.py # Data models
279
+ │ ├── errors.py # Custom exceptions
280
+ │ ├── cli.py # CLI interface
281
+ │ ├── memory/
282
+ │ │ ├── base.py # Memory interface
283
+ │ │ └── conversation.py # Memory implementations
284
+ │ └── llm/
285
+ │ ├── base.py # LLM backend interface
286
+ │ ├── openai_backend.py
287
+ │ └── anthropic_backend.py
288
+ ├── tests/
289
+ ├── examples/
290
+ ├── pyproject.toml
291
+ └── README.md
292
+ ```
293
+
294
+ ## License
295
+
296
+ MIT
@@ -0,0 +1,254 @@
1
+ # agent-weave
2
+
3
+ `agent-weave` is a lightweight Python framework for building AI agents with tool use, ReAct reasoning, multi-agent teams, memory, and guardrails.
4
+
5
+ No bloat. No magic. Just clean, composable building blocks.
6
+
7
+ ## Features
8
+
9
+ - **`@tool` decorator** — Turn any Python function into an agent tool with auto-generated schemas.
10
+ - **ReAct loop** — Built-in Reasoning + Acting engine with configurable iteration limits.
11
+ - **Multi-agent teams** — Sequential pipelines, round-robin, and router-based orchestration.
12
+ - **Memory** — Conversation memory and sliding-window memory with system prompt preservation.
13
+ - **Guardrails** — PII detection, blocked words, regex filters, token budgets, and max-length checks.
14
+ - **Provider backends** — OpenAI, Anthropic, and any OpenAI-compatible API.
15
+ - **Async-first** — Full `async/await` support for every operation.
16
+ - **CLI** — Run agents and chat from the terminal.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install -e .
22
+ ```
23
+
24
+ With OpenAI support:
25
+
26
+ ```bash
27
+ pip install -e ".[openai]"
28
+ ```
29
+
30
+ With Anthropic support:
31
+
32
+ ```bash
33
+ pip install -e ".[anthropic]"
34
+ ```
35
+
36
+ Install everything:
37
+
38
+ ```bash
39
+ pip install -e ".[all]"
40
+ ```
41
+
42
+ For development:
43
+
44
+ ```bash
45
+ pip install -e ".[dev,all]"
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ import os
52
+ from agent_weave import Agent, tool
53
+ from agent_weave.llm.openai_backend import OpenAIBackend
54
+
55
+ @tool(description="Get the weather for a city")
56
+ def get_weather(city: str) -> str:
57
+ return f"72°F and sunny in {city}"
58
+
59
+ @tool(description="Calculate a math expression")
60
+ def calculator(expression: str) -> str:
61
+ return str(eval(expression))
62
+
63
+ agent = Agent(
64
+ name="assistant",
65
+ llm=OpenAIBackend(api_key=os.environ["OPENAI_API_KEY"]),
66
+ tools=[get_weather, calculator],
67
+ system_prompt="You are a helpful assistant. Use tools when needed.",
68
+ )
69
+
70
+ result = agent.run("What's the weather in NYC and what is 42 * 17?")
71
+ print(result.output)
72
+ print(f"Steps: {result.total_iterations}, Tokens: {result.total_tokens:,}")
73
+ ```
74
+
75
+ ## The `@tool` Decorator
76
+
77
+ Turn any function into a tool. Schemas are auto-generated from type hints:
78
+
79
+ ```python
80
+ from agent_weave import tool
81
+
82
+ @tool(description="Search the web for a query")
83
+ def web_search(query: str, max_results: int = 5) -> str:
84
+ return f"Results for: {query} (limit {max_results})"
85
+
86
+ # Access the generated schema
87
+ print(web_search.schema.to_openai_tool())
88
+ ```
89
+
90
+ ## Multi-Agent Teams
91
+
92
+ Chain agents in a pipeline, round-robin, or route to specialists:
93
+
94
+ ```python
95
+ from agent_weave import Agent, Team, Strategy
96
+ from agent_weave.llm.openai_backend import OpenAIBackend
97
+
98
+ backend = OpenAIBackend(api_key=os.environ["OPENAI_API_KEY"])
99
+
100
+ researcher = Agent(name="researcher", llm=backend,
101
+ system_prompt="Research the topic. Provide key facts.")
102
+
103
+ writer = Agent(name="writer", llm=backend,
104
+ system_prompt="Write a blog post from the research provided.")
105
+
106
+ editor = Agent(name="editor", llm=backend,
107
+ system_prompt="Polish and improve the writing.")
108
+
109
+ # Sequential: researcher -> writer -> editor
110
+ team = Team(
111
+ agents=[researcher, writer, editor],
112
+ strategy=Strategy.SEQUENTIAL,
113
+ )
114
+ result = team.run("AI agents in 2025")
115
+ print(result.final_output)
116
+ ```
117
+
118
+ ### Router Strategy
119
+
120
+ ```python
121
+ router = Agent(name="router", llm=backend,
122
+ system_prompt="You route tasks to the right specialist.")
123
+
124
+ team = Team(
125
+ agents=[researcher, writer],
126
+ strategy=Strategy.ROUTER,
127
+ router=router,
128
+ )
129
+ result = team.run("Write a poem about AI")
130
+ ```
131
+
132
+ ## Memory
133
+
134
+ ```python
135
+ from agent_weave.memory import ConversationMemory, SlidingWindowMemory
136
+
137
+ # Unlimited memory
138
+ agent = Agent(name="bot", llm=backend, memory=ConversationMemory())
139
+
140
+ # Fixed window (keeps last 20 messages + system prompt)
141
+ agent = Agent(name="bot", llm=backend,
142
+ memory=SlidingWindowMemory(max_messages=20))
143
+ ```
144
+
145
+ ## Guardrails
146
+
147
+ ```python
148
+ from agent_weave import (
149
+ Agent, MaxLengthGuardrail, PIIGuardrail, BlockedWordsGuardrail,
150
+ )
151
+
152
+ agent = Agent(
153
+ name="safe-bot",
154
+ llm=backend,
155
+ token_budget=10_000, # Max 10k tokens per run
156
+ output_guardrails=[
157
+ MaxLengthGuardrail(max_chars=5_000),
158
+ PIIGuardrail(redact=True),
159
+ BlockedWordsGuardrail(words=["confidential", "password"]),
160
+ ],
161
+ )
162
+ ```
163
+
164
+ ## Conversational Chat
165
+
166
+ ```python
167
+ agent = Agent(name="chatbot", llm=backend,
168
+ system_prompt="You are a friendly chatbot.")
169
+
170
+ # chat() preserves history across calls
171
+ agent.chat("Hello!")
172
+ agent.chat("What did I just say?") # Agent remembers
173
+ agent.reset() # Clear conversation
174
+ ```
175
+
176
+ ## Async Support
177
+
178
+ ```python
179
+ import asyncio
180
+
181
+ async def main():
182
+ result = await agent.arun("Summarize AI trends")
183
+ print(result.output)
184
+
185
+ asyncio.run(main())
186
+ ```
187
+
188
+ ## Anthropic Backend
189
+
190
+ ```python
191
+ from agent_weave.llm.anthropic_backend import AnthropicBackend
192
+
193
+ agent = Agent(
194
+ name="claude-agent",
195
+ llm=AnthropicBackend(api_key=os.environ["ANTHROPIC_API_KEY"]),
196
+ system_prompt="You are helpful.",
197
+ )
198
+ result = agent.run("Explain quantum computing simply.")
199
+ ```
200
+
201
+ ## CLI
202
+
203
+ ```bash
204
+ # Set your API key
205
+ export OPENAI_API_KEY="sk-..."
206
+
207
+ # Run a single task
208
+ agent-weave run "What are the top 3 AI trends in 2025?"
209
+
210
+ # Interactive chat
211
+ agent-weave chat
212
+
213
+ # Library info
214
+ agent-weave info
215
+ ```
216
+
217
+ ## Run Tests
218
+
219
+ ```bash
220
+ pip install -e ".[dev]"
221
+ python -m pytest
222
+ ```
223
+
224
+ ## Project Structure
225
+
226
+ ```
227
+ agent-weave/
228
+ ├── src/agent_weave/
229
+ │ ├── __init__.py # Public API
230
+ │ ├── agent.py # Core Agent class
231
+ │ ├── tool.py # @tool decorator & Tool class
232
+ │ ├── react.py # ReAct reasoning engine
233
+ │ ├── team.py # Multi-agent orchestration
234
+ │ ├── guardrails.py # Safety & validation
235
+ │ ├── config.py # Settings
236
+ │ ├── models.py # Data models
237
+ │ ├── errors.py # Custom exceptions
238
+ │ ├── cli.py # CLI interface
239
+ │ ├── memory/
240
+ │ │ ├── base.py # Memory interface
241
+ │ │ └── conversation.py # Memory implementations
242
+ │ └── llm/
243
+ │ ├── base.py # LLM backend interface
244
+ │ ├── openai_backend.py
245
+ │ └── anthropic_backend.py
246
+ ├── tests/
247
+ ├── examples/
248
+ ├── pyproject.toml
249
+ └── README.md
250
+ ```
251
+
252
+ ## License
253
+
254
+ MIT
@@ -0,0 +1,86 @@
1
+ """Advanced tools and guardrails example for agent-weave."""
2
+
3
+ import json
4
+ import os
5
+
6
+ from agent_weave import (
7
+ Agent,
8
+ BlockedWordsGuardrail,
9
+ MaxLengthGuardrail,
10
+ PIIGuardrail,
11
+ tool,
12
+ )
13
+ from agent_weave.llm.openai_backend import OpenAIBackend
14
+
15
+ # --- Custom tools ---
16
+
17
+
18
+ @tool(description="Search a knowledge base for information about a topic")
19
+ def knowledge_search(query: str) -> str:
20
+ """Simulated knowledge base search."""
21
+ kb = {
22
+ "python": "Python is a high-level programming language known for simplicity.",
23
+ "rust": "Rust is a systems language focused on safety and performance.",
24
+ "agents": "AI agents are autonomous systems that can reason and use tools.",
25
+ "rag": "RAG combines retrieval with generation for grounded AI responses.",
26
+ }
27
+ results = []
28
+ for key, value in kb.items():
29
+ if key in query.lower():
30
+ results.append(value)
31
+ return "\n".join(results) if results else "No results found."
32
+
33
+
34
+ @tool(
35
+ name="create_summary",
36
+ description="Create a structured JSON summary from text",
37
+ )
38
+ def create_summary(text: str, max_points: int = 3) -> str:
39
+ """Create a bullet-point summary."""
40
+ sentences = [s.strip() for s in text.split(".") if s.strip()]
41
+ points = sentences[:max_points]
42
+ return json.dumps({"summary_points": points, "total_sentences": len(sentences)})
43
+
44
+
45
+ @tool(description="Get the current date and time")
46
+ def get_current_time() -> str:
47
+ from datetime import datetime, timezone
48
+ return datetime.now(timezone.utc).isoformat()
49
+
50
+
51
+ # --- Agent with guardrails ---
52
+
53
+
54
+ def main() -> None:
55
+ backend = OpenAIBackend(
56
+ api_key=os.environ["OPENAI_API_KEY"],
57
+ default_model="gpt-4o-mini",
58
+ )
59
+
60
+ agent = Agent(
61
+ name="safe-researcher",
62
+ llm=backend,
63
+ tools=[knowledge_search, create_summary, get_current_time],
64
+ system_prompt=(
65
+ "You are a research assistant with access to a knowledge base. "
66
+ "Always search before answering. Provide factual, concise answers."
67
+ ),
68
+ max_iterations=8,
69
+ token_budget=10_000,
70
+ output_guardrails=[
71
+ MaxLengthGuardrail(max_chars=5_000),
72
+ PIIGuardrail(redact=True),
73
+ BlockedWordsGuardrail(words=["confidential", "secret"]),
74
+ ],
75
+ verbose=True,
76
+ )
77
+
78
+ result = agent.run("What can you tell me about Python and AI agents?")
79
+ print(f"\nAnswer: {result.output}")
80
+ print(f"\nSteps: {result.total_iterations}")
81
+ print(f"Tokens: {result.total_tokens:,}")
82
+ print(f"Tool calls: {result.total_tool_calls}")
83
+
84
+
85
+ if __name__ == "__main__":
86
+ main()