techtide-botkit 0.3.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.
botkit/skill.py ADDED
@@ -0,0 +1,137 @@
1
+ """Skills: folders of instructions the model loads on demand (like Claude Skills).
2
+
3
+ skills/
4
+ pirate/SKILL.md <- frontmatter (name, description) + instructions
5
+ sql-helper/SKILL.md
6
+ tone.md <- a single .md file also works
7
+
8
+ Only the name + description sit in the system prompt; the full text is loaded via the `load_skill` tool
9
+ when the model decides it needs it, so many skills cost almost no context.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import re
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Any, Iterable
17
+
18
+ from .tool import Tool
19
+
20
+
21
+ @dataclass
22
+ class Skill:
23
+ name: str
24
+ description: str
25
+ body: str
26
+ path: Path | None = None
27
+
28
+
29
+ def _parse(text: str, default_name: str, path: Path | None) -> Skill:
30
+ meta: dict[str, str] = {}
31
+ body = text
32
+ m = re.match(r"^---\s*\n(.*?)\n---\s*\n?(.*)$", text, re.S)
33
+ if m:
34
+ for line in m.group(1).splitlines():
35
+ if ":" in line and not line.startswith((" ", "\t", "#")):
36
+ key, _, val = line.partition(":")
37
+ meta[key.strip().lower()] = val.strip().strip("\"'")
38
+ body = m.group(2)
39
+ body = body.strip()
40
+ first_line = next((ln.strip("# ").strip() for ln in body.splitlines() if ln.strip()), "")
41
+ return Skill(meta.get("name") or default_name, meta.get("description") or first_line[:200], body, path)
42
+
43
+
44
+ def load_skills(source: Any) -> list[Skill]:
45
+ """Accepts a folder path, a Skill, or a list of those."""
46
+ if source is None:
47
+ return []
48
+ if isinstance(source, Skill):
49
+ return [source]
50
+ if isinstance(source, (str, Path)):
51
+ root = Path(source).expanduser()
52
+ if not root.exists():
53
+ raise FileNotFoundError(f"Skills path not found: {root}")
54
+ if root.is_file():
55
+ return [_parse(root.read_text(encoding="utf-8"), root.stem, root)]
56
+ if (root / "SKILL.md").is_file():
57
+ return [_parse((root / "SKILL.md").read_text(encoding="utf-8"), root.name, root)]
58
+ skills: list[Skill] = []
59
+ for child in sorted(root.iterdir()):
60
+ if child.is_dir() and (child / "SKILL.md").is_file():
61
+ skills.append(_parse((child / "SKILL.md").read_text(encoding="utf-8"), child.name, child))
62
+ elif child.is_file() and child.suffix == ".md" and child.name.upper() != "README.MD":
63
+ skills.append(_parse(child.read_text(encoding="utf-8"), child.stem, child))
64
+ return skills
65
+ if isinstance(source, Iterable):
66
+ out: list[Skill] = []
67
+ for item in source:
68
+ out.extend(load_skills(item))
69
+ return out
70
+ raise TypeError(f"Unsupported skills source: {source!r}")
71
+
72
+
73
+ class SkillBook:
74
+ def __init__(self, skills: list[Skill]) -> None:
75
+ self.skills = {s.name: s for s in skills}
76
+
77
+ def __bool__(self) -> bool:
78
+ return bool(self.skills)
79
+
80
+ def prompt(self) -> str:
81
+ lines = "\n".join(f"- {s.name}: {s.description}" for s in self.skills.values())
82
+ return (
83
+ "You have these skills. When a request matches one, call `load_skill` with its name "
84
+ "and follow the instructions it returns.\n" + lines
85
+ )
86
+
87
+ def tool(self) -> Tool:
88
+ skills = self.skills
89
+
90
+ def load_skill(name: str) -> str:
91
+ if name not in skills:
92
+ raise ValueError(f"unknown skill '{name}'. Available: {', '.join(skills)}")
93
+ return skills[name].body
94
+
95
+ return Tool(
96
+ name="load_skill",
97
+ description="Load the full instructions of a skill by name.",
98
+ parameters={
99
+ "type": "object",
100
+ "properties": {"name": {"type": "string", "enum": list(skills), "description": "Skill name"}},
101
+ "required": ["name"],
102
+ },
103
+ fn=load_skill,
104
+ )
105
+
106
+
107
+ BUNDLED_DIR = Path(__file__).parent / "skills"
108
+
109
+
110
+ def bundled_names() -> list[str]:
111
+ return sorted(d.name for d in BUNDLED_DIR.iterdir() if (d / "SKILL.md").is_file())
112
+
113
+
114
+ def resolve_skills(spec: Any) -> list[Skill]:
115
+ """What Agent(skills=...) accepts:
116
+
117
+ True the bundled skills
118
+ "my_skills/" a folder (or one SKILL.md / .md file) of your own
119
+ "research" one bundled skill by name
120
+ Skill(...) an inline skill
121
+ [True, "my_skills/"] any mix of the above
122
+ """
123
+ if spec in (None, False):
124
+ return []
125
+ if spec is True:
126
+ return load_skills(BUNDLED_DIR)
127
+ if isinstance(spec, Skill):
128
+ return [spec]
129
+ if isinstance(spec, (str, Path)):
130
+ text = str(spec)
131
+ if not Path(text).expanduser().exists() and text in bundled_names():
132
+ return load_skills(BUNDLED_DIR / text)
133
+ return load_skills(spec)
134
+ out: list[Skill] = []
135
+ for item in spec:
136
+ out.extend(resolve_skills(item))
137
+ return out
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: coding
3
+ description: Use when asked to write, change, or explain code, scripts, or small programs.
4
+ ---
5
+ 1. Give complete, runnable code, not fragments. Include imports, a clear entry point, and the exact command to run it.
6
+ 2. Handle the obvious failures (missing input, bad values, network errors) with clear messages. Keep functions small and names clear.
7
+ 3. Save longer code to a file with `write_file` instead of pasting it into chat. Change existing files with `edit_file`.
8
+ 4. If a shell is available, run it once and fix what breaks. If not, re-read the code for syntax errors, wrong names and missing imports.
9
+ 5. Match the user's language, framework and style. Do not add libraries or features that were not asked for.
10
+ 6. Keep the explanation short: what it does, how to run it, and any setup needed (keys, installs).
@@ -0,0 +1,9 @@
1
+ ---
2
+ name: data-analysis
3
+ description: Use when asked to analyze, summarize, clean or compare data from a CSV, spreadsheet or list of numbers.
4
+ ---
5
+ 1. Look at the data first: columns, row count, types, missing values, obvious outliers. Use `read_file` (it reads .xlsx and .csv) or a script if a shell is available.
6
+ 2. Compute results with code or `calculate`, never in your head. For large files use a script, not the conversation.
7
+ 3. Sanity-check: do totals add up, are the units right, does the result make sense in size?
8
+ 4. Report the answer first, then how you got it, then caveats (missing data, assumptions, small samples). Do not claim causes the data cannot show.
9
+ 5. When a table or chart helps, save it as a file (`create_xlsx`, or a script's output) and name it.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: debugging
3
+ description: Use when something fails, throws an error, or behaves differently than expected.
4
+ ---
5
+ 1. Read the whole error message and traceback. The last lines and the first line of your own code in the trace matter most.
6
+ 2. Reproduce it. If you cannot run the code, ask for the exact input and the full error text.
7
+ 3. Form one hypothesis, find the evidence in the code (`search_files`, `read_file`), and confirm it before changing anything.
8
+ 4. Make the smallest change that fixes the root cause. Change one thing at a time, then run again.
9
+ 5. Explain in two or three sentences what was wrong and why the fix works.
10
+ 6. If it still fails, report what you tried and what you learned instead of guessing again.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: planning
3
+ description: Use for any task with several steps or several deliverables, before starting work.
4
+ ---
5
+ 1. Restate the goal in one sentence, including the output the user expects (file, answer, code).
6
+ 2. If something essential is missing and a wrong guess would be costly, ask ONE short question. Otherwise pick the most reasonable reading, say which one you took, and continue.
7
+ 3. Break the work into 3-7 concrete steps. Do the research or data gathering first, then build, then check.
8
+ 4. Do the steps in order. Do not repeat a tool call that already gave you the answer.
9
+ 5. The last step is always checking the result (see the `verify-work` skill).
10
+ 6. Finish with what you produced and one natural next step. Do not narrate every step you took.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: presentations
3
+ description: Use when asked to make slides, a deck, or a presentation.
4
+ ---
5
+ 1. Ask nothing unless the topic is missing. Default to 6-10 slides.
6
+ 2. Structure: title slide, agenda or the key message, one idea per content slide, a summary or next steps slide.
7
+ 3. Each slide: a clear title that states the point, 3-5 bullets, each under about 12 words. No paragraphs on slides.
8
+ 4. Put the longer explanation in the speaker notes.
9
+ 5. Build it with `create_pptx` (slides is a list of objects with title, bullets, subtitle, notes).
10
+ 6. Read it back with `read_file` to check slide count and text, then tell the user the file name.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: research
3
+ description: Use for questions about current facts, prices, news, comparisons, or anything that may have changed. Look things up before answering.
4
+ ---
5
+ 1. Decide what must be looked up: anything time-sensitive, numeric, or that you are not sure about. Do not answer those from memory.
6
+ 2. Search with specific queries (`web_search`), then open the best 2-4 pages (`fetch_url`). Prefer official and primary sources.
7
+ 3. Cross-check important claims against a second source. If sources disagree, say so instead of picking silently.
8
+ 4. Give the answer first, then the supporting detail. Put dates next to time-sensitive facts.
9
+ 5. End with a short "Sources:" list of the URLs you actually read. Never invent a URL, quote or statistic.
10
+ 6. If something could not be verified, say so plainly.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: spreadsheets
3
+ description: Use when asked to build a spreadsheet, budget, tracker, schedule, or any table with calculations.
4
+ ---
5
+ 1. Design the columns first: one header row, one record per row, one fact per cell. No merged cells or blank spacer rows.
6
+ 2. Use formulas for anything calculated (totals, averages, percentages), written as strings starting with "=". Do not paste computed numbers.
7
+ 3. Keep inputs (rates, assumptions) in their own sheet or block and reference them from formulas.
8
+ 4. Create the file with `create_xlsx` (sheets is a mapping of sheet name to rows).
9
+ 5. Read it back with `read_file` and check that the formulas point at the right cells.
10
+ 6. Tell the user the file name and what each sheet contains.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: summarizing
3
+ description: Use when asked to summarize, shorten, or extract the key points of a text, document, page or conversation.
4
+ ---
5
+ 1. Read all of it first (`read_file` or `fetch_url`). Do not summarize from the title.
6
+ 2. Lead with the single most important conclusion in one or two sentences.
7
+ 3. Then the key points, as few as will do. Keep numbers, names and dates exactly as written.
8
+ 4. Make the length proportional: a page becomes a paragraph, a long report becomes about ten lines.
9
+ 5. Add nothing that is not in the source. If the source is unclear or one-sided, say so.
10
+ 6. Offer a longer version only if there is a real reason to.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: verify-work
3
+ description: Use before giving a final answer or delivering a file or code. Check the work instead of assuming it is right.
4
+ ---
5
+ 1. Re-read the request and tick off every requirement. Missing parts get fixed now, not mentioned later.
6
+ 2. Numbers: recompute them with `calculate` or code. Do not trust mental arithmetic.
7
+ 3. Files you created: open them again with `read_file` and confirm the content and the file name.
8
+ 4. Code: run it if a shell is available, or at least read it once for syntax errors, wrong names and missing imports.
9
+ 5. Facts: make sure each one comes from a source you actually read or from the user.
10
+ 6. Report honestly. If something was not verified or could not be done, say exactly what and why.
@@ -0,0 +1,10 @@
1
+ ---
2
+ name: writing-documents
3
+ description: Use when asked to write a report, memo, proposal, letter, plan, article or any document the user will keep or send.
4
+ ---
5
+ 1. Work out the audience and purpose first. Then choose a structure: title, short summary at the top, headings, then the detail.
6
+ 2. Lead with the conclusion or the ask. Keep paragraphs short, use bullets only for parallel items, use a table for comparisons.
7
+ 3. Be specific: real names, numbers and dates from the user or from sources. Never pad with generic filler.
8
+ 4. If the user wants a file, write the content in simple markdown and create it with `create_docx` (headings with #, bullets with -, **bold**, | tables |).
9
+ 5. Read the file back with `read_file` and fix mistakes. Tell the user the file name.
10
+ 6. Match the user's language and tone. For emails and messages, just give the text; no file needed.
botkit/tool.py ADDED
@@ -0,0 +1,198 @@
1
+ """Turn any Python function into an LLM tool."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import inspect
6
+ import json
7
+ import re
8
+ import threading
9
+ import types as _types
10
+ import typing
11
+ from dataclasses import dataclass
12
+ from typing import Any, Callable
13
+
14
+ _PRIMS = {str: "string", int: "integer", float: "number", bool: "boolean"}
15
+
16
+
17
+ def _schema_for(tp: Any) -> dict:
18
+ """JSON-schema fragment for a Python type hint."""
19
+ if tp is inspect.Parameter.empty or tp is Any:
20
+ return {"type": "string"}
21
+ if tp in _PRIMS:
22
+ return {"type": _PRIMS[tp]}
23
+ origin, args = typing.get_origin(tp), typing.get_args(tp)
24
+ if tp in (list, tuple, set, frozenset) or origin in (list, tuple, set, frozenset):
25
+ schema: dict = {"type": "array"}
26
+ if args and args[0] is not Ellipsis:
27
+ schema["items"] = _schema_for(args[0])
28
+ return schema
29
+ if tp is dict or origin is dict:
30
+ return {"type": "object"}
31
+ if origin is typing.Literal:
32
+ return {"enum": list(args)}
33
+ if origin is typing.Union or origin is getattr(_types, "UnionType", object()):
34
+ opts = [a for a in args if a is not type(None)]
35
+ if len(opts) == 1:
36
+ return _schema_for(opts[0])
37
+ return {"anyOf": [_schema_for(a) for a in opts]}
38
+ return {"type": "string"}
39
+
40
+
41
+ def _parse_doc(doc: str | None) -> tuple[str, dict[str, str]]:
42
+ """Split a docstring into (description, {param: description}) - Google style `Args:`."""
43
+ if not doc:
44
+ return "", {}
45
+ doc = inspect.cleandoc(doc)
46
+ parts = re.split(r"\n\s*(?:Args|Arguments|Parameters):\s*\n", doc, maxsplit=1)
47
+ desc = parts[0].strip()
48
+ params: dict[str, str] = {}
49
+ if len(parts) > 1:
50
+ for m in re.finditer(r"^\s*(\w+)\s*(?:\([^)]*\))?:\s*(.+)$", parts[1], re.M):
51
+ params[m.group(1)] = m.group(2).strip()
52
+ return desc, params
53
+
54
+
55
+ def to_text(value: Any) -> str:
56
+ """Convert any tool return value to the string the model will read."""
57
+ if value is None:
58
+ return "OK"
59
+ if isinstance(value, str):
60
+ return value
61
+ try:
62
+ return json.dumps(value, ensure_ascii=False, default=str)
63
+ except Exception:
64
+ return str(value)
65
+
66
+
67
+ def _run_async(awaitable: Any) -> Any:
68
+ """Run a coroutine to completion from sync code (works even inside a running loop)."""
69
+ box: dict[str, Any] = {}
70
+
71
+ async def _wrap() -> Any:
72
+ return await awaitable
73
+
74
+ def target() -> None:
75
+ try:
76
+ box["value"] = asyncio.run(_wrap())
77
+ except BaseException as e: # noqa: BLE001
78
+ box["error"] = e
79
+
80
+ t = threading.Thread(target=target)
81
+ t.start()
82
+ t.join()
83
+ if "error" in box:
84
+ raise box["error"]
85
+ return box["value"]
86
+
87
+
88
+ @dataclass
89
+ class Tool:
90
+ """A function the model may call. Build one with the @tool decorator."""
91
+
92
+ name: str
93
+ description: str
94
+ parameters: dict
95
+ fn: Callable[..., Any]
96
+ sensitive: bool = False # sensitive tools go through the Agent's `approve` callback, if one is set
97
+
98
+ def spec(self) -> dict:
99
+ params = self.parameters or {"type": "object", "properties": {}}
100
+ params.setdefault("type", "object")
101
+ params.setdefault("properties", {})
102
+ return {
103
+ "type": "function",
104
+ "function": {"name": self.name, "description": self.description, "parameters": params},
105
+ }
106
+
107
+ def __call__(self, *args: Any, **kwargs: Any) -> Any:
108
+ return self.fn(*args, **kwargs)
109
+
110
+ def _coerce(self, args: dict) -> dict:
111
+ """Models often send "5" for an int or 5 for a string; fix the easy cases."""
112
+ props = (self.parameters or {}).get("properties", {})
113
+ out = dict(args)
114
+ for key, val in args.items():
115
+ kind = props.get(key, {}).get("type")
116
+ try:
117
+ if isinstance(val, str):
118
+ if kind == "integer":
119
+ out[key] = int(val)
120
+ elif kind == "number":
121
+ out[key] = float(val)
122
+ elif kind == "boolean" and val.strip().lower() in ("true", "false"):
123
+ out[key] = val.strip().lower() == "true"
124
+ elif kind in ("array", "object"):
125
+ out[key] = json.loads(val)
126
+ elif kind == "string" and isinstance(val, (int, float)) and not isinstance(val, bool):
127
+ out[key] = str(val)
128
+ elif kind == "integer" and isinstance(val, float) and val.is_integer():
129
+ out[key] = int(val)
130
+ except ValueError:
131
+ pass
132
+ return out
133
+
134
+ def run(self, args: dict) -> Any:
135
+ out = self.fn(**self._coerce(args))
136
+ if inspect.isawaitable(out):
137
+ out = _run_async(out)
138
+ return out
139
+
140
+
141
+ def tool(
142
+ fn: Callable[..., Any] | None = None,
143
+ *,
144
+ name: str | None = None,
145
+ description: str | None = None,
146
+ sensitive: bool = False,
147
+ ):
148
+ """Decorator: `@tool` on a function -> a Tool (schema built from type hints + docstring).
149
+
150
+ @tool
151
+ def weather(city: str) -> str:
152
+ '''Get the weather for a city.
153
+ Args:
154
+ city: City name, e.g. "Lahore".
155
+ '''
156
+ """
157
+
158
+ def wrap(f: Callable[..., Any]) -> Tool:
159
+ if isinstance(f, Tool):
160
+ return f
161
+ sig = inspect.signature(f)
162
+ try:
163
+ hints = typing.get_type_hints(f)
164
+ except Exception:
165
+ hints = {}
166
+ doc_desc, doc_params = _parse_doc(inspect.getdoc(f))
167
+ props: dict[str, dict] = {}
168
+ required: list[str] = []
169
+ for pname, p in sig.parameters.items():
170
+ if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD):
171
+ continue
172
+ schema = dict(_schema_for(hints.get(pname, p.annotation)))
173
+ if pname in doc_params:
174
+ schema["description"] = doc_params[pname]
175
+ props[pname] = schema
176
+ if p.default is p.empty:
177
+ required.append(pname)
178
+ params: dict[str, Any] = {"type": "object", "properties": props}
179
+ if required:
180
+ params["required"] = required
181
+ tool_name = name or getattr(f, "__name__", "tool")
182
+ return Tool(tool_name, description or doc_desc or tool_name, params, f, sensitive)
183
+
184
+ return wrap(fn) if fn is not None else wrap
185
+
186
+
187
+ def as_tool(obj: Any) -> Tool:
188
+ """Accept a Tool or a plain callable."""
189
+ if isinstance(obj, Tool):
190
+ return obj
191
+ if callable(obj):
192
+ return tool(obj)
193
+ raise TypeError(f"Cannot use {obj!r} as a tool (expected a function or Tool)")
194
+
195
+
196
+ def clip(text: str, limit: int) -> str:
197
+ """Shorten long text and say how much was cut."""
198
+ return text if len(text) <= limit else text[:limit] + f"\n...[truncated {len(text) - limit} characters]"
@@ -0,0 +1,42 @@
1
+ """The bundled tools (12), in five groups. Turn them on with Agent(tools=...):
2
+
3
+ tools=True all of them
4
+ tools=["files", "web"] whole groups
5
+ tools=["read_file", "calculate"] single tools
6
+ tools=["files", my_function] mix with your own functions
7
+
8
+ files list_files read_file write_file edit_file search_files
9
+ docs create_docx create_xlsx create_pptx (pip install 'botkit[docs]')
10
+ web fetch_url web_search
11
+ shell run_command (only exists with Agent(shell=...))
12
+ util calculate
13
+ """
14
+ from __future__ import annotations
15
+
16
+ from typing import Any
17
+
18
+ from ..tool import Tool
19
+ from . import docs, files, shell, util, web
20
+
21
+ GROUPS = {"files": files.make, "docs": docs.make, "web": web.make, "shell": shell.make, "util": util.make}
22
+
23
+
24
+ def build(policy: Any, sandbox: Any, select: Any) -> list[Tool]:
25
+ """Create bundled tools. `select` is True (everything) or a list of group / tool names."""
26
+ by_group = {name: factory(policy, sandbox) for name, factory in GROUPS.items()}
27
+ if select is True:
28
+ return [t for tools in by_group.values() for t in tools]
29
+ by_name = {t.name: t for tools in by_group.values() for t in tools}
30
+ chosen: dict[str, Tool] = {}
31
+ for item in select:
32
+ if item in by_group:
33
+ chosen.update({t.name: t for t in by_group[item]})
34
+ elif item in by_name:
35
+ chosen[item] = by_name[item]
36
+ elif item == "run_command":
37
+ raise ValueError("'run_command' needs an environment: Agent(shell='local') or Agent(shell='docker')")
38
+ else:
39
+ raise ValueError(
40
+ f"Unknown bundled tool or group {item!r}. Groups: {sorted(GROUPS)}. Tools: {sorted(by_name)}"
41
+ )
42
+ return list(chosen.values())