pyagentkit 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.
pyagentkit/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ from .agent import Agent
2
+ from .definitions import (
3
+ ToolResult,
4
+ RegisteredCommand,
5
+ AgentResponse,
6
+ AgentDependencies,
7
+ ToolReturnValue,
8
+ )
9
+ from .exceptions import (
10
+ AgentExceptionError,
11
+ AgentExceptionFatal,
12
+ ToolExceptionError,
13
+ ToolExceptionFatal,
14
+ )
15
+
16
+ __all__ = [
17
+ "Agent",
18
+ "ToolResult",
19
+ "RegisteredCommand",
20
+ "AgentResponse",
21
+ "AgentDependencies",
22
+ "ToolReturnValue",
23
+ "AgentExceptionError",
24
+ "AgentExceptionFatal",
25
+ "ToolExceptionError",
26
+ "ToolExceptionFatal",
27
+ ]
pyagentkit/agent.py ADDED
@@ -0,0 +1,493 @@
1
+ import re
2
+ import json
3
+ import inspect
4
+ from typing import (
5
+ ClassVar,
6
+ Generic,
7
+ Literal,
8
+ Type,
9
+ TypeVar,
10
+ Union,
11
+ get_args,
12
+ get_origin,
13
+ )
14
+
15
+ import ollama
16
+ from pydantic import BaseModel, ValidationError
17
+ from pydantic_core import ErrorDetails
18
+ from .definitions import (
19
+ AgentDependencies,
20
+ AgentResponse,
21
+ RegisteredTool,
22
+ TypeTool,
23
+ tool_call_schema,
24
+ ToolReturnValue,
25
+ )
26
+ from .exceptions import (
27
+ AgentExceptionError,
28
+ AgentExceptionFatal,
29
+ ToolExceptionError,
30
+ ToolExceptionFatal,
31
+ )
32
+
33
+ T = TypeVar("T", bound=AgentResponse)
34
+
35
+
36
+ class Agent(Generic[T]):
37
+ """Allows easier agent creation"""
38
+
39
+ base_system_prompt: str
40
+ llm_name: str
41
+ response_model: Type[T]
42
+ instructions: str | None
43
+ agent_name: str
44
+ message_history: list[dict[str, str]]
45
+ tool_retries: int
46
+ response_retries: int
47
+ class_tools: ClassVar[dict[str, RegisteredTool]] = {}
48
+ instance_tools: dict[str, RegisteredTool]
49
+ tool_try: int = 0
50
+ dependencies: Type[AgentDependencies]
51
+ num_ctx: int
52
+ ollama_client: ollama.Client
53
+
54
+ def _verify_ollama_environment(self) -> None:
55
+ """
56
+ Checks if the Ollama server is reachable and if the llm is downloaded.
57
+ """
58
+ try:
59
+ # A simple request like list local models is a good way to verify connection
60
+ model_list = self.ollama_client.list()
61
+ models = []
62
+ for entry in model_list.get("models"):
63
+ models.append(entry.get("model"))
64
+ if self.llm_name not in models:
65
+ raise RuntimeError(
66
+ f"Model {self.llm_name} not found locally",
67
+ f"Run `ollama pull {self.llm_name}` to install `{self.llm_name}`",
68
+ )
69
+
70
+ except ConnectionError as e:
71
+ raise RuntimeError(
72
+ f"Failed connecting to Ollama: {e}.",
73
+ "Please ensure Ollama is running and the host address is correct",
74
+ )
75
+
76
+ def _build_schema_prompt(self) -> str:
77
+ """
78
+ Generates human-readable JSON examples from the response model.
79
+ Handles the discriminated union (final vs tool_call) and appends
80
+ any extra fields defined on subclasses.
81
+ """
82
+ # Discover extra fields added by the subclass (e.g. test: int, sub: SubResponse)
83
+ base_fields = set(AgentResponse.model_fields.keys())
84
+ extra_fields = {
85
+ k: v
86
+ for k, v in self.response_model.model_fields.items()
87
+ if k not in base_fields
88
+ }
89
+
90
+ def placeholder(annotation) -> object:
91
+ """Produce a sensible placeholder for a given type annotation."""
92
+ origin = get_origin(annotation)
93
+ if origin is Union:
94
+ # Pick the first non-None arg
95
+ args = [a for a in get_args(annotation) if a is not type(None)]
96
+ return placeholder(args[0]) if args else None
97
+ if origin is Literal:
98
+ return get_args(annotation)[0]
99
+ if annotation is str:
100
+ return "string"
101
+ if annotation is int:
102
+ return "int"
103
+ if annotation is float:
104
+ return "float"
105
+ if annotation is bool:
106
+ return "boolean"
107
+ if annotation is list or origin is list:
108
+ inner = get_args(annotation)
109
+ return [placeholder(inner[0])] if inner else []
110
+ if annotation is dict or origin is dict:
111
+ return {}
112
+ # Nested Pydantic model - recurse
113
+ try:
114
+ if issubclass(annotation, BaseModel):
115
+ return _pydantic_example(annotation)
116
+ except TypeError:
117
+ pass
118
+ return None
119
+
120
+ def _pydantic_example(model: type[BaseModel]) -> dict:
121
+ result = {}
122
+ for name, field in model.model_fields.items():
123
+ result[name] = placeholder(field.annotation)
124
+ return result
125
+
126
+ # Build the two canonical examples
127
+ tool_example = {
128
+ "response": {
129
+ "type": "tool_call",
130
+ "tool_call": {
131
+ "name": "<tool_name>",
132
+ "params": [{"name": "<param_name>", "value": "<param_value>"}],
133
+ },
134
+ },
135
+ "message": "<why you're calling the tool>",
136
+ }
137
+ final_example = {
138
+ "response": {"type": "final"},
139
+ "message": "<your answer or result of your operation(s)>",
140
+ }
141
+
142
+ # Append any subclass-defined extra fields to both examples
143
+ for key, field in extra_fields.items():
144
+ tool_example[key] = placeholder(field.annotation)
145
+ final_example[key] = placeholder(field.annotation)
146
+
147
+ lines = [
148
+ "## Response format",
149
+ "You MUST respond with one of these two JSON shapes and nothing else.",
150
+ "",
151
+ "When calling a tool:",
152
+ "```json",
153
+ json.dumps(tool_example, indent=2),
154
+ "```",
155
+ "",
156
+ "When giving a final answer:",
157
+ "```json",
158
+ json.dumps(final_example, indent=2),
159
+ "```",
160
+ ]
161
+
162
+ return "\n".join(lines)
163
+
164
+ def _get_tools(self):
165
+ """Gets the tooling data for the system prompt"""
166
+ result = "## Tools At Your Disposal"
167
+ all_tools = {**self.instance_tools, **self.class_tools}
168
+ for _, value in all_tools.items():
169
+ sig = inspect.signature(value.function)
170
+ params = {k: v for k, v in sig.parameters.items() if k != value.deps_param}
171
+ clean_sig = f"({', '.join(str(p) for p in params.values())})"
172
+ result += f"\n- {value.name} {clean_sig} | Description: {value.desc}"
173
+ return result
174
+
175
+ @staticmethod
176
+ def _parse_tool(tool: TypeTool) -> RegisteredTool:
177
+ """Helper for parsing tools"""
178
+ name = tool.__name__
179
+ doc = tool.__doc__
180
+ if doc is None:
181
+ raise RuntimeError(f"Tool `{name}` has no docstring")
182
+
183
+ signature = inspect.signature(tool)
184
+ params = list(signature.parameters.values())
185
+ need_deps = (
186
+ len(params) > 0
187
+ and params[0].annotation is not inspect.Parameter.empty
188
+ and isinstance(params[0].annotation, type)
189
+ and issubclass(params[0].annotation, AgentDependencies)
190
+ )
191
+
192
+ return RegisteredTool(
193
+ name=name,
194
+ signature=str(signature),
195
+ function=tool,
196
+ desc=doc,
197
+ need_deps=need_deps,
198
+ deps_param=params[0].name if need_deps else None,
199
+ )
200
+
201
+ def _add_tool(self, tool: TypeTool) -> None:
202
+ new_tool = self._parse_tool(tool)
203
+ self.instance_tools[new_tool.name] = new_tool
204
+
205
+ @classmethod
206
+ def register_tool(cls, tool: TypeTool):
207
+ """Decorator: Adds a class-wide tool"""
208
+ new_tool = Agent._parse_tool(tool)
209
+ cls.class_tools[new_tool.name] = new_tool
210
+ return tool
211
+
212
+ def __init__(
213
+ self,
214
+ llm_name: str,
215
+ tool_retries: int = 3,
216
+ response_retries: int = 3,
217
+ system_prompt: str | None = "",
218
+ instructions: str | None = "",
219
+ agent_name: str | None = None,
220
+ response_model: Type[T] = AgentResponse,
221
+ num_ctx: int = 8192,
222
+ ollama_url: str | None = None,
223
+ tools: list[TypeTool] | None = None,
224
+ ):
225
+ self.base_system_prompt = system_prompt or ""
226
+ self.llm_name = llm_name
227
+ self.response_model = response_model
228
+ self.instructions = instructions or ""
229
+ self.agent_name = agent_name or self.llm_name
230
+ self.tool_retries = tool_retries
231
+ self.response_retries = response_retries
232
+ self.message_history = []
233
+ self.num_ctx = num_ctx
234
+ self.instance_tools = {}
235
+ self.ollama_url = ollama_url
236
+ self.ollama_client = (
237
+ ollama.Client(host=self.ollama_url) if ollama_url else ollama.Client()
238
+ )
239
+ self._verify_ollama_environment()
240
+ if tools:
241
+ for tool in tools:
242
+ self._add_tool(tool)
243
+
244
+ def __init_subclass__(cls, **kwargs) -> None:
245
+ super().__init_subclass__(**kwargs)
246
+ cls.class_tools = {}
247
+
248
+ def _print_validation_errors(self, errors: list[ErrorDetails]) -> str:
249
+ """
250
+ Returns the ValidationError errors in a readable message format.
251
+ Used to create readable messages for the agent
252
+
253
+ Args:
254
+ errors (list[ErrorDetails]): Validation error details
255
+ Returns:
256
+ (str): Printable message
257
+ """
258
+ result = "Your response failed validation, handle the following issues and generate your answer with the same `type`\nEncountered errors:"
259
+ for error in errors:
260
+ result += f"\nType: {error['type']}"
261
+ result += f"\nField: {'.'.join(map(str, error['loc']))}"
262
+ result += f"\nError message: {error['msg']}"
263
+ result += "\nCRITICAL: Fix the errors and respond ONLY with valid JSON. Make sure you close out your curly braces ('{'). Do NOT include any markdown formatting."
264
+ return result
265
+
266
+ def _strip_markdown_formatting(self, message: str) -> str:
267
+ """
268
+ Strips the (```) from the provided message
269
+ Args:
270
+ message (str): Message to trim
271
+ Returns:
272
+ (str): Stripped message
273
+ """
274
+ raw = message.strip()
275
+ if "```" in raw:
276
+ match = re.search(r"```(?:json)?\s*(.*?)```", raw, re.DOTALL)
277
+ raw = match.group(1).strip() if match else raw
278
+ return raw
279
+
280
+ def _validate_agent_logic(
281
+ self,
282
+ response: AgentResponse,
283
+ ) -> None:
284
+ """
285
+ Hook for validating agent-specific logic
286
+ Raise AgentExceptionError on fail
287
+ """
288
+ pass
289
+
290
+ def _handle_tool_call(self, tool_call: tool_call_schema) -> None:
291
+ all_tools = {**self.class_tools, **self.instance_tools}
292
+ while self.tool_try < self.tool_retries:
293
+ tool_name = tool_call.name
294
+ tool_params = tool_call.params
295
+ # Find if there is such tool registered
296
+ accepted_tool = all_tools.get(tool_name)
297
+ if accepted_tool is None:
298
+ raise ToolExceptionError(
299
+ f"Tool `{tool_call.name}` not found, check the tool name and respond with a valid tool name",
300
+ )
301
+ print(
302
+ f"\n[Info]: Agent {self.agent_name} wants to call tool {tool_name} with params:"
303
+ )
304
+ for param in tool_params:
305
+ print("-", param)
306
+ choice = input("Allow tool call? (Y/n): ").lower().strip()
307
+ if choice not in ["y", ""]:
308
+ print("[Info]: Cancelled tool call")
309
+ self.message_history.append(
310
+ {
311
+ "role": "user",
312
+ "content": f"Tool `{tool_name}` with params `{tool_params}` has been rejected by the user. Generate final response saying that the user has rejected the tool call",
313
+ }
314
+ )
315
+ self.tool_try += 1
316
+ return
317
+
318
+ # Handle tool arguments
319
+ kwargs = {p.name: p.value for p in tool_params}
320
+ if accepted_tool.need_deps:
321
+ if self.current_deps is None:
322
+ raise ToolExceptionFatal(
323
+ f"Tool `{tool_name}` requires dependencies but none were provided to handle_response"
324
+ )
325
+ if accepted_tool.deps_param is None:
326
+ raise ToolExceptionFatal(
327
+ f"Registration Error (Tool `{tool_name}` requires dependencies but has none)"
328
+ )
329
+ kwargs[accepted_tool.deps_param] = self.current_deps
330
+
331
+ # Validate kwargs against the actual function signature
332
+ sig = inspect.signature(accepted_tool.function)
333
+ valid_params = set(sig.parameters.keys())
334
+ provided_params = set(kwargs.keys())
335
+
336
+ unknown = provided_params - valid_params
337
+ missing = {
338
+ name
339
+ for name, param in sig.parameters.items()
340
+ if param.default is inspect.Parameter.empty
341
+ and name not in provided_params
342
+ }
343
+
344
+ if unknown or missing:
345
+ parts = []
346
+ if unknown:
347
+ unknown_message = f"Unknown parameters {sorted(unknown)}"
348
+ print(f"[ERROR] {unknown_message}")
349
+ parts.append(unknown_message)
350
+ if missing:
351
+ missing_message = f"Missing required parameters: {sorted(missing)}"
352
+ print(f"[ERROR] {missing_message}")
353
+ parts.append(missing_message)
354
+ valid_list = [
355
+ f"{name}: {inspect.formatannotation(p.annotation) if p.annotation is not inspect.Parameter.empty else 'any'}"
356
+ for name, p in sig.parameters.items()
357
+ ]
358
+ parts.append(f"Valid parameters for `{tool_name}`: {valid_list}")
359
+ raise ToolExceptionError(". ".join(parts))
360
+
361
+ # Call tool and get return value
362
+ try:
363
+ tool_return = accepted_tool.function(**kwargs)
364
+ except TypeError as exc:
365
+ print(
366
+ f"[ERROR]: Called tool `{tool_name}` with invalid arguments `{kwargs}`"
367
+ )
368
+ raise ToolExceptionError(
369
+ f"Tool `{tool_name}` call failed with invalid arguments: {exc}. "
370
+ f"Check parameter names and types against the tool signature."
371
+ )
372
+ tool_return_val = tool_return.return_value
373
+ tool_content = tool_return.content
374
+ if tool_return_val == ToolReturnValue.fatal:
375
+ raise ToolExceptionFatal(tool_content)
376
+ elif tool_return_val == ToolReturnValue.error:
377
+ self.message_history.append(
378
+ {
379
+ "role": "user",
380
+ "content": f"Tool Result: ERROR\nTool Message: {tool_content}\nRead the tool message and act accordingly",
381
+ }
382
+ )
383
+ raise ToolExceptionError(tool_content)
384
+ elif tool_return_val == ToolReturnValue.success:
385
+ self.message_history.append(
386
+ {
387
+ "role": "user",
388
+ "content": f"""Tool Result: SUCCESS
389
+ Tool Response: {tool_content}
390
+
391
+ If task is done, generate `final` response and stop.""",
392
+ }
393
+ )
394
+ self.tool_try = 0
395
+ return
396
+ raise ToolExceptionFatal(
397
+ f"[FATAL]: Agent {self.agent_name} has failed to generate successful tool call in {self.tool_retries} tries"
398
+ )
399
+
400
+ def handle_response(self, prompt: str, deps: AgentDependencies | None = None) -> T:
401
+ response_try = 0
402
+ # Send prompt to agent
403
+ # print(f"[DEBUG]: System prompt: {self.message_history[0]}")
404
+ compiled_system_prompt = f"""{self.base_system_prompt}
405
+
406
+ {self._build_schema_prompt()}
407
+
408
+ {self._get_tools()}
409
+
410
+ ## Crucial Rules - Rules To Abide By
411
+ - DON'T include any explanations, introductions or apologies.
412
+ - DON'T explain the process, execute it.
413
+ - Make sure your responses are perfect JSON objects (No missing braces, commas or quotes)
414
+ - Make sure your responses are matching with the schemas you've been given (No missing or invalid fields)
415
+ - DO NOT USE ``` CODE BLOCKS OR \"\"\" MULTI-LINE STRINGS, ONLY SINGLE LINE STRINGS ARE ALLOWED.
416
+ - Do NOT use placeholder values for any function parameter or file content.
417
+ - ONLY use paths that are in the format of `./target/path` or `target/path`
418
+ - DO NOT USE ANY NON-EXISTING TOOLS. DON'T MAKE UP TOOL NAMES.
419
+ """
420
+ self.current_deps = deps
421
+ if len(self.message_history) == 0:
422
+ self.message_history.append(
423
+ {"role": "system", "content": compiled_system_prompt}
424
+ )
425
+ self.message_history.append(
426
+ {"role": "user", "content": prompt},
427
+ )
428
+ while response_try < self.response_retries:
429
+ # print(f"[DEBUG]: Last Message: {self.message_history[-1]}")
430
+ # print(f"[DEBUG]: Response Try: {response_try}, Tool Try: {self.tool_try}")
431
+ try:
432
+ response = self.ollama_client.chat(
433
+ model=self.llm_name,
434
+ messages=self.message_history,
435
+ options={"num_ctx": self.num_ctx},
436
+ )
437
+ content = response.message.content
438
+ print(f"[DEBUG] Content:\n{content}")
439
+ if content is None:
440
+ raise RuntimeError(
441
+ f"Failed to get response from agent {self.agent_name}"
442
+ )
443
+
444
+ # Append the assistant message because it doesn't know that it
445
+ # actually did anything
446
+ self.message_history.append({"role": "assistant", "content": content})
447
+
448
+ # Get rid of markdown fences because some models are stupid
449
+ # stripped = self._strip_markdown_formatting(message=content)
450
+ # print(f"[DEBUG] Stripped: {stripped}")
451
+ # validated = self.response_model.model_validate_json(stripped)
452
+
453
+ validated = self.response_model.model_validate_json(content)
454
+ # print(f"[DEBUG] Validated Response:\n{validated}\n")
455
+ # If the response is "done", return
456
+ print(f"[{self.agent_name}]: {validated.message}")
457
+ self._validate_agent_logic(response=validated)
458
+ if validated.response.type == "final":
459
+ return validated
460
+ if validated.response.type == "tool_call":
461
+ response_try = 0
462
+ tool_call = validated.response.tool_call
463
+ # Check if a tool call is present in a `tool_call` typed response
464
+ if tool_call:
465
+ self._handle_tool_call(tool_call=tool_call)
466
+
467
+ except ValidationError as exc:
468
+ print(
469
+ f"[DEBUG] Validation error string: {self._print_validation_errors(exc.errors())}"
470
+ )
471
+ self.message_history.append(
472
+ {
473
+ "role": "user",
474
+ "content": self._print_validation_errors(exc.errors()),
475
+ }
476
+ )
477
+ response_try += 1
478
+ except AgentExceptionError as exc:
479
+ self.message_history.append({"role": "user", "content": exc.message})
480
+ response_try += 1
481
+ except ToolExceptionError as exc:
482
+ self.message_history.append({"role": "user", "content": exc.message})
483
+ self.tool_try += 1
484
+ except (AgentExceptionFatal, ToolExceptionFatal) as exc:
485
+ self.tool_try = 0
486
+ raise RuntimeError(exc.message)
487
+ except Exception as exc:
488
+ self.tool_try = 0
489
+ raise RuntimeError(f"Unhandled exception: {str(exc)}")
490
+
491
+ raise RuntimeError(
492
+ f"[ERROR] Agent {self.agent_name} failed to provide a valid response after {self.response_retries} attempts."
493
+ )
@@ -0,0 +1,90 @@
1
+ """Contains enums, schemas, types and global values"""
2
+
3
+ from enum import Enum
4
+ from typing import Any, Callable, Literal, Union
5
+
6
+ from pydantic import BaseModel, Field
7
+
8
+
9
+ class ToolReturnValue(Enum):
10
+ """
11
+ The return value for a tool result
12
+ """
13
+
14
+ success = "success"
15
+ error = "error"
16
+ fatal = "fatal"
17
+
18
+
19
+ type TypeTool = Callable[..., ToolResult]
20
+
21
+
22
+ class tool_params(BaseModel):
23
+ """
24
+ Tool parameters
25
+ """
26
+
27
+ name: str
28
+ value: Any
29
+
30
+
31
+ class tool_call_schema(BaseModel):
32
+ """
33
+ Tool call object
34
+ """
35
+
36
+ name: str
37
+ params: list[tool_params]
38
+
39
+
40
+ class FinalResponse(BaseModel):
41
+ type: Literal["final"]
42
+
43
+
44
+ class ToolCallResponse(BaseModel):
45
+ type: Literal["tool_call"]
46
+ tool_call: tool_call_schema
47
+
48
+
49
+ class AgentResponse(BaseModel):
50
+ response: Union[FinalResponse, ToolCallResponse] = Field(discriminator="type")
51
+ message: str
52
+
53
+
54
+ class AgentDependencies(BaseModel):
55
+ """
56
+ Basic dependencies class which other dependency classes will
57
+ inherit from.
58
+ """
59
+
60
+ prompt: str = Field(description="The prompt to be used")
61
+
62
+
63
+ class ToolResult(BaseModel):
64
+ """
65
+ Return value of a tool function
66
+ """
67
+
68
+ return_value: ToolReturnValue
69
+ content: str
70
+
71
+
72
+ class RegisteredTool(BaseModel):
73
+ model_config = {"arbitrary_types_allowed": True}
74
+ name: str
75
+ signature: str
76
+ desc: str
77
+ function: TypeTool
78
+ need_deps: bool = False
79
+ deps_param: str | None = None
80
+
81
+
82
+ class RegisteredCommand(BaseModel):
83
+ """
84
+ Defines a command which can be called by 'execute_command'
85
+ """
86
+
87
+ name: str = Field(description="Name of the registered command")
88
+ accepted_args: list[str] = Field(description="Accepted arguments or flags")
89
+ # True if non-flag args are supposed to be treated as paths
90
+ accepts_file_path: bool = False
@@ -0,0 +1,30 @@
1
+ class AgentExceptionError(Exception):
2
+ """Recoverable response exception"""
3
+
4
+ def __init__(self, message: str):
5
+ self.message = message
6
+ super().__init__(self.message)
7
+
8
+
9
+ class AgentExceptionFatal(Exception):
10
+ """Irrecoverable response exception"""
11
+
12
+ def __init__(self, message: str):
13
+ self.message = message
14
+ super().__init__(self.message)
15
+
16
+
17
+ class ToolExceptionError(Exception):
18
+ """Recoverable tool calling exception"""
19
+
20
+ def __init__(self, message: str):
21
+ self.message = message
22
+ super().__init__(self.message)
23
+
24
+
25
+ class ToolExceptionFatal(Exception):
26
+ """Irrecoverable tool exception"""
27
+
28
+ def __init__(self, message: str):
29
+ self.message = message
30
+ super().__init__(self.message)
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyagentkit
3
+ Version: 0.1.0
4
+ Summary: Agent toolkit for Ollama
5
+ Project-URL: Homepage, https://github.com/TarikEren/pyagentkit
6
+ Project-URL: Issues, https://github.com/TarikEren/pyagentkit/issues
7
+ Author-email: Tarık Eren Tosun <tarikerentosun@outlook.com>
8
+ Maintainer-email: Tarık Eren Tosun <tarikerentosun@outlook.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: agent,agentic,ai,ollama
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.12
15
+ Requires-Dist: build>=1.4.2
16
+ Requires-Dist: ollama>=0.6.1
17
+ Requires-Dist: pydantic>=2.12.5
18
+ Requires-Dist: twine>=6.2.0
19
+ Description-Content-Type: text/markdown
20
+
21
+ ## PyAgentKit
22
+
23
+ Lightweight library for creating tool-enabled AI agents using Ollama. Including the ones that do not have tool calling capabilities.
24
+
25
+ - Refer to [USAGE.md](./USAGE.md) for usage details.
26
+
27
+ ## Why this exists
28
+
29
+ - To give models which cannot produce structured tool calls a way to call custom made Python tooling.
30
+
31
+ ## Features
32
+
33
+ - Works with models that have no native tool calling
34
+ - Easy, simple tool creation and robust execution loop
35
+ - Schema validation for tool inputs
36
+ - Structured and validated agent responses
37
+
38
+ ## Installation (Not in PyPI yet)
39
+
40
+ ```bash
41
+ pip install pyagentkit
42
+ ```
43
+
44
+ ## Example
45
+
46
+ ```python
47
+ from ollama_agentkit import Agent, tool, AgentResponse
48
+
49
+ # Custom output class to manipulate LLM output
50
+ class CustomOutput(AgentResponse):
51
+ sum_result: int
52
+
53
+ agent = Agent(
54
+ # Works with any LLM's locally downloaded in your ollama server
55
+ llm_name="qwen2.5-coder:7b",
56
+
57
+ # Custom response models are allowed for responses
58
+ response_model=CustomOutput
59
+ )
60
+
61
+ # Easy to define tooling with decorator `register_tool`
62
+ @agent.register_tool
63
+ def add_tool(n1: int, n2: int):
64
+ """Adds two numbers""" # All tooling must have a one-liner docstring that defines what the function does
65
+ # Every tool must return a `ToolResult` object
66
+ return ToolResult(
67
+ return_value=ToolReturnValue.success, # Status of the return | Can be either success, error or fatal.
68
+ # Affects how the tool call is processed.
69
+ content=f"Result: {n1 + n2}" # The part which the agent will read
70
+ )
71
+
72
+ # Messages get printed during the response handling
73
+ result = agent.handle_response(prompt="What is 2 + 2")
74
+ print(result.sum_result)
75
+
76
+ ```
77
+
78
+ ## Design goals
79
+ - Simple to use
80
+ - Model-agnostic where possible
81
+ - Strict validation
82
+ - Clear separation of agent logic and application logic
83
+
84
+ ## Limitations
85
+ - Tool reliability depends on prompt and model instruction-following quality
86
+ - Some models may need stronger prompting
87
+ - Long tool chains may need retry logic or guardrails
@@ -0,0 +1,8 @@
1
+ pyagentkit/__init__.py,sha256=0xC3aS5w-T--jdicBcAV-hOHVHwRknNLHW6i4wsVLrI,528
2
+ pyagentkit/agent.py,sha256=eQ_d5PlDl6UrSQVB5YkZWWE4lfKsaYMvd1cXmdrkedk,19467
3
+ pyagentkit/definitions.py,sha256=GV3kxc4VElvYSXnuE1dM1Bgt8vF_ONRpX6FnGJItSYQ,1793
4
+ pyagentkit/exceptions.py,sha256=QQeOwwvSkdoB66I0L1Yk8oOgm0C2m2g3_F_mYb2_EL0,760
5
+ pyagentkit-0.1.0.dist-info/METADATA,sha256=k3S6K2c524U6yLGyD_eVQ5WP6ykX4tT3TeBwehlqrWc,2757
6
+ pyagentkit-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
7
+ pyagentkit-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
8
+ pyagentkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.