toprompt 0.0.1__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.
- toprompt/__init__.py +5 -0
- toprompt/cli_types.py +165 -0
- toprompt/dataclass_types.py +30 -0
- toprompt/py.typed +0 -0
- toprompt/sqlite_types.py +241 -0
- toprompt/sqlmodel_types.py +59 -0
- toprompt/to_prompt.py +267 -0
- toprompt-0.0.1.dist-info/METADATA +84 -0
- toprompt-0.0.1.dist-info/RECORD +11 -0
- toprompt-0.0.1.dist-info/WHEEL +4 -0
- toprompt-0.0.1.dist-info/licenses/LICENSE +22 -0
toprompt/__init__.py
ADDED
toprompt/cli_types.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from clinspector.models.commandinfo import CommandInfo
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@runtime_checkable
|
|
12
|
+
class ClickCommandLike(Protocol):
|
|
13
|
+
"""Protocol for Click-like command objects."""
|
|
14
|
+
|
|
15
|
+
name: str # Click commands always have a name
|
|
16
|
+
commands: dict[str, Any] # Groups have subcommands
|
|
17
|
+
params: list[Any] # Click commands have params
|
|
18
|
+
help: str | None # Click commands can have help text
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@runtime_checkable
|
|
22
|
+
class TyperCommandLike(Protocol):
|
|
23
|
+
"""Protocol for Typer-like command objects."""
|
|
24
|
+
|
|
25
|
+
info: Any # Typer instances have an info attribute
|
|
26
|
+
registered_callback: Any # And a registered_callback
|
|
27
|
+
registered_commands: dict[str, Any] # Commands are stored here
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def is_click_command(obj: Any) -> bool:
|
|
31
|
+
"""Check if object looks like a Click command/group.
|
|
32
|
+
|
|
33
|
+
Tries to detect Click commands by their distinctive attributes,
|
|
34
|
+
without requiring Click to be installed.
|
|
35
|
+
"""
|
|
36
|
+
return isinstance(obj, ClickCommandLike) and obj.__class__.__module__.startswith(
|
|
37
|
+
"click"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_typer_command(obj: Any) -> bool:
|
|
42
|
+
"""Check if object looks like a Typer app.
|
|
43
|
+
|
|
44
|
+
Tries to detect Typer apps by their distinctive attributes,
|
|
45
|
+
without requiring Typer to be installed.
|
|
46
|
+
"""
|
|
47
|
+
return isinstance(obj, TyperCommandLike) and obj.__class__.__module__.startswith(
|
|
48
|
+
"typer"
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def is_cli_object(obj: Any) -> bool:
|
|
53
|
+
"""Check if object is a supported CLI framework object.
|
|
54
|
+
|
|
55
|
+
Safely checks for installed CLI frameworks before doing type checks.
|
|
56
|
+
Prevents import errors if a framework is not installed.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
obj: Object to check
|
|
60
|
+
"""
|
|
61
|
+
# ArgumentParser is from stdlib, so we can always check it
|
|
62
|
+
if importlib.util.find_spec("argparse"):
|
|
63
|
+
import argparse
|
|
64
|
+
|
|
65
|
+
if isinstance(obj, argparse.ArgumentParser):
|
|
66
|
+
return True
|
|
67
|
+
|
|
68
|
+
# Check Click
|
|
69
|
+
if importlib.util.find_spec("click"):
|
|
70
|
+
import click
|
|
71
|
+
|
|
72
|
+
if isinstance(obj, click.Group):
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
# Check Typer
|
|
76
|
+
if importlib.util.find_spec("typer"):
|
|
77
|
+
import typer
|
|
78
|
+
|
|
79
|
+
if isinstance(obj, typer.Typer):
|
|
80
|
+
return True
|
|
81
|
+
|
|
82
|
+
# Check Cleo
|
|
83
|
+
if importlib.util.find_spec("cleo"):
|
|
84
|
+
from cleo.application import Application # type: ignore
|
|
85
|
+
|
|
86
|
+
if isinstance(obj, Application):
|
|
87
|
+
return True
|
|
88
|
+
|
|
89
|
+
# Check Cappa
|
|
90
|
+
if importlib.util.find_spec("cappa"):
|
|
91
|
+
from cappa import Command as CappaCommand # type: ignore
|
|
92
|
+
|
|
93
|
+
if isinstance(obj, CappaCommand):
|
|
94
|
+
return True
|
|
95
|
+
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def format_cli_command(
|
|
100
|
+
info: CommandInfo,
|
|
101
|
+
*,
|
|
102
|
+
indent_level: int = 0,
|
|
103
|
+
) -> str:
|
|
104
|
+
"""Format a CommandInfo object into a prompt-friendly string recursively.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
info: The CommandInfo object to format
|
|
108
|
+
indent_level: Current indentation level for nested commands
|
|
109
|
+
"""
|
|
110
|
+
indent = " " * indent_level
|
|
111
|
+
lines = [f"{indent}Command: {info.name}"]
|
|
112
|
+
|
|
113
|
+
if info.description:
|
|
114
|
+
lines.extend(["", f"{indent}Description: {info.description}"])
|
|
115
|
+
|
|
116
|
+
if info.usage:
|
|
117
|
+
lines.extend(["", f"{indent}Usage: {info.usage}"])
|
|
118
|
+
|
|
119
|
+
if info.params:
|
|
120
|
+
lines.extend(["", f"{indent}Parameters:"])
|
|
121
|
+
for param in info.params:
|
|
122
|
+
# Format parameter line
|
|
123
|
+
parts = []
|
|
124
|
+
|
|
125
|
+
# Add options/name
|
|
126
|
+
if param.opts:
|
|
127
|
+
parts.append(f"{', '.join(param.opts)}")
|
|
128
|
+
else:
|
|
129
|
+
parts.append(param.name)
|
|
130
|
+
|
|
131
|
+
# Add type info
|
|
132
|
+
if param.type:
|
|
133
|
+
parts.append(f"({param.type})")
|
|
134
|
+
|
|
135
|
+
# Add help text
|
|
136
|
+
if param.help:
|
|
137
|
+
parts.append(f"- {param.help}")
|
|
138
|
+
|
|
139
|
+
# Add constraints
|
|
140
|
+
constraints = []
|
|
141
|
+
if param.required:
|
|
142
|
+
constraints.append("required")
|
|
143
|
+
if param.multiple:
|
|
144
|
+
constraints.append("multiple values allowed")
|
|
145
|
+
if param.is_flag:
|
|
146
|
+
constraints.append("flag")
|
|
147
|
+
if param.default is not None:
|
|
148
|
+
constraints.append(f"default: {param.default}")
|
|
149
|
+
|
|
150
|
+
if constraints:
|
|
151
|
+
parts.append(f"[{', '.join(constraints)}]")
|
|
152
|
+
|
|
153
|
+
lines.append(f"{indent} {' '.join(parts)}")
|
|
154
|
+
|
|
155
|
+
if info.subcommands:
|
|
156
|
+
lines.extend(["", f"{indent}Subcommands:"])
|
|
157
|
+
for subcmd in info.subcommands.values():
|
|
158
|
+
# Recursively format each subcommand with increased indentation
|
|
159
|
+
subcommand_text = format_cli_command(
|
|
160
|
+
subcmd,
|
|
161
|
+
indent_level=indent_level + 1,
|
|
162
|
+
)
|
|
163
|
+
lines.extend(["", subcommand_text])
|
|
164
|
+
|
|
165
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, TypeVar
|
|
4
|
+
|
|
5
|
+
from fieldz import fields
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
T = TypeVar("T")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def format_dataclass_like(obj: Any) -> str:
|
|
12
|
+
"""Format object instance showing structure and current values."""
|
|
13
|
+
try:
|
|
14
|
+
obj_fields = fields(obj)
|
|
15
|
+
except TypeError:
|
|
16
|
+
return f"Unable to inspect fields of {type(obj)}"
|
|
17
|
+
|
|
18
|
+
lines = [f"{type(obj).__name__}:\n{type(obj).__doc__}\n"]
|
|
19
|
+
|
|
20
|
+
for field in obj_fields:
|
|
21
|
+
if field.name.startswith("_"):
|
|
22
|
+
continue
|
|
23
|
+
value = getattr(obj, field.name)
|
|
24
|
+
if field.description:
|
|
25
|
+
lines.append(f"- {field.name} = {value!r} ({field.description})")
|
|
26
|
+
else:
|
|
27
|
+
type_name = field.type if field.type else "any"
|
|
28
|
+
lines.append(f"- {field.name} = {value!r} ({type_name})")
|
|
29
|
+
|
|
30
|
+
return "\n".join(lines)
|
toprompt/py.typed
ADDED
|
File without changes
|
toprompt/sqlite_types.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Protocol, TypedDict, runtime_checkable
|
|
5
|
+
|
|
6
|
+
import upath
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
import os
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@runtime_checkable
|
|
14
|
+
class InMemoryDatabaseLike(Protocol):
|
|
15
|
+
"""Protocol for in-memory database-like objects."""
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
def in_memory(self) -> bool: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@runtime_checkable
|
|
22
|
+
class FileDatabaseLike(Protocol):
|
|
23
|
+
"""Protocol for file-based database-like objects."""
|
|
24
|
+
|
|
25
|
+
@property
|
|
26
|
+
def _filename(self) -> str | None: ...
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ColumnInfo(TypedDict):
|
|
30
|
+
"""Information about a SQLite column."""
|
|
31
|
+
|
|
32
|
+
name: str
|
|
33
|
+
type: str
|
|
34
|
+
notnull: bool
|
|
35
|
+
default: str | None
|
|
36
|
+
pk: bool
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class ForeignKeyInfo(TypedDict):
|
|
40
|
+
"""Information about a SQLite foreign key."""
|
|
41
|
+
|
|
42
|
+
from_table: str
|
|
43
|
+
from_col: str
|
|
44
|
+
to_table: str
|
|
45
|
+
to_col: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class IndexInfo(TypedDict):
|
|
49
|
+
"""Information about a SQLite index."""
|
|
50
|
+
|
|
51
|
+
name: str
|
|
52
|
+
table: str
|
|
53
|
+
unique: bool
|
|
54
|
+
columns: list[str]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def is_sqlite_db(obj: Any) -> bool:
|
|
58
|
+
"""Check if object is a SQLite database."""
|
|
59
|
+
return isinstance(obj, sqlite3.Connection)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def get_db_path(conn: sqlite3.Connection) -> str:
|
|
63
|
+
"""Get the path for a SQLite database connection."""
|
|
64
|
+
try:
|
|
65
|
+
cursor = conn.cursor()
|
|
66
|
+
cursor.execute("PRAGMA database_list")
|
|
67
|
+
# This returns rows with (seq, name, file) for each database
|
|
68
|
+
for _, name, file_path in cursor.fetchall():
|
|
69
|
+
if name == "main": # main database
|
|
70
|
+
return file_path or ":memory:"
|
|
71
|
+
except sqlite3.Error:
|
|
72
|
+
pass
|
|
73
|
+
return ":memory:" # fallback to memory if we can't determine
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def get_sqlite_schema(db: str | os.PathLike[str] | sqlite3.Connection) -> str:
|
|
77
|
+
"""Generate human-readable documentation from SQLite database.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
db: Path to SQLite database file or Connection object
|
|
81
|
+
"""
|
|
82
|
+
if isinstance(db, sqlite3.Connection):
|
|
83
|
+
conn = db
|
|
84
|
+
should_close = False
|
|
85
|
+
else:
|
|
86
|
+
path = upath.UPath(db)
|
|
87
|
+
if not path.exists():
|
|
88
|
+
msg = f"Database file not found: {path}"
|
|
89
|
+
raise FileNotFoundError(msg)
|
|
90
|
+
conn = sqlite3.connect(path)
|
|
91
|
+
should_close = True
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
cursor = conn.cursor()
|
|
95
|
+
# Get all tables
|
|
96
|
+
tables = get_tables(cursor)
|
|
97
|
+
if not tables:
|
|
98
|
+
return "Database contains no tables."
|
|
99
|
+
|
|
100
|
+
lines = ["SQLite Database Schema:"]
|
|
101
|
+
|
|
102
|
+
# Process each table
|
|
103
|
+
for table in tables:
|
|
104
|
+
lines.extend(get_table_info(cursor, table))
|
|
105
|
+
lines.append("") # Empty line between tables
|
|
106
|
+
|
|
107
|
+
return "\n".join(lines)
|
|
108
|
+
|
|
109
|
+
finally:
|
|
110
|
+
if should_close:
|
|
111
|
+
conn.close()
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def get_tables(cursor: sqlite3.Cursor) -> list[str]:
|
|
115
|
+
"""Get all table names from database."""
|
|
116
|
+
cursor.execute(
|
|
117
|
+
"""
|
|
118
|
+
SELECT name FROM sqlite_master
|
|
119
|
+
WHERE type='table'
|
|
120
|
+
AND name NOT LIKE 'sqlite_%'
|
|
121
|
+
ORDER BY name
|
|
122
|
+
"""
|
|
123
|
+
)
|
|
124
|
+
return [row[0] for row in cursor.fetchall()]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def get_table_info(cursor: sqlite3.Cursor, table: str) -> list[str]:
|
|
128
|
+
"""Get detailed information about a specific table."""
|
|
129
|
+
# Get column information
|
|
130
|
+
cursor.execute(f"PRAGMA table_info({table})")
|
|
131
|
+
columns: list[ColumnInfo] = [
|
|
132
|
+
{
|
|
133
|
+
"name": row[1],
|
|
134
|
+
"type": row[2],
|
|
135
|
+
"notnull": bool(row[3]),
|
|
136
|
+
"default": row[4],
|
|
137
|
+
"pk": bool(row[5]),
|
|
138
|
+
}
|
|
139
|
+
for row in cursor.fetchall()
|
|
140
|
+
]
|
|
141
|
+
|
|
142
|
+
# Get foreign keys
|
|
143
|
+
cursor.execute(f"PRAGMA foreign_key_list({table})")
|
|
144
|
+
foreign_keys: list[ForeignKeyInfo] = [
|
|
145
|
+
{
|
|
146
|
+
"from_table": table,
|
|
147
|
+
"from_col": row[3],
|
|
148
|
+
"to_table": row[2],
|
|
149
|
+
"to_col": row[4],
|
|
150
|
+
}
|
|
151
|
+
for row in cursor.fetchall()
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
# Get indices
|
|
155
|
+
cursor.execute(
|
|
156
|
+
"""
|
|
157
|
+
SELECT name, sql FROM sqlite_master
|
|
158
|
+
WHERE type='index'
|
|
159
|
+
AND tbl_name=?
|
|
160
|
+
AND name NOT LIKE 'sqlite_%'
|
|
161
|
+
""",
|
|
162
|
+
(table,),
|
|
163
|
+
)
|
|
164
|
+
indices = get_index_info(cursor, table)
|
|
165
|
+
|
|
166
|
+
# Format table documentation
|
|
167
|
+
lines = [f"\nTable: {table}"]
|
|
168
|
+
|
|
169
|
+
# Columns
|
|
170
|
+
lines.append("\nColumns:")
|
|
171
|
+
for col in columns:
|
|
172
|
+
parts = [f"- {col['name']}: {col['type']}"]
|
|
173
|
+
properties = []
|
|
174
|
+
|
|
175
|
+
if col["pk"]:
|
|
176
|
+
properties.append("primary key")
|
|
177
|
+
if col["notnull"]:
|
|
178
|
+
properties.append("not null")
|
|
179
|
+
if col["default"] is not None:
|
|
180
|
+
properties.append(f"default: {col['default']}")
|
|
181
|
+
|
|
182
|
+
if properties:
|
|
183
|
+
parts.append(f"({', '.join(properties)})")
|
|
184
|
+
lines.append(" ".join(parts))
|
|
185
|
+
|
|
186
|
+
# Foreign Keys
|
|
187
|
+
if foreign_keys:
|
|
188
|
+
lines.append("\nForeign Keys:")
|
|
189
|
+
lines.extend(
|
|
190
|
+
f"- {fk['from_col']} -> {fk['to_table']}.{fk['to_col']}"
|
|
191
|
+
for fk in foreign_keys
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# Indices
|
|
195
|
+
if indices:
|
|
196
|
+
lines.append("\nIndices:")
|
|
197
|
+
for idx in indices:
|
|
198
|
+
unique = "UNIQUE " if idx["unique"] else ""
|
|
199
|
+
cols = ", ".join(idx["columns"])
|
|
200
|
+
lines.append(f"- {idx['name']}: {unique}({cols})")
|
|
201
|
+
|
|
202
|
+
return lines
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def get_index_info(cursor: sqlite3.Cursor, table: str) -> list[IndexInfo]:
|
|
206
|
+
"""Get information about indices on a table."""
|
|
207
|
+
cursor.execute(
|
|
208
|
+
"""
|
|
209
|
+
SELECT name, sql FROM sqlite_master
|
|
210
|
+
WHERE type='index'
|
|
211
|
+
AND tbl_name=?
|
|
212
|
+
AND name NOT LIKE 'sqlite_%'
|
|
213
|
+
""",
|
|
214
|
+
(table,),
|
|
215
|
+
)
|
|
216
|
+
indices: list[IndexInfo] = []
|
|
217
|
+
|
|
218
|
+
for name, sql in cursor.fetchall():
|
|
219
|
+
if not sql:
|
|
220
|
+
continue
|
|
221
|
+
|
|
222
|
+
# Parse SQL to extract column names and uniqueness
|
|
223
|
+
sql = sql.upper()
|
|
224
|
+
unique = "UNIQUE " in sql
|
|
225
|
+
# Extract column list from parentheses
|
|
226
|
+
cols_start = sql.find("(")
|
|
227
|
+
cols_end = sql.rfind(")")
|
|
228
|
+
if cols_start == -1 or cols_end == -1:
|
|
229
|
+
continue
|
|
230
|
+
|
|
231
|
+
cols = sql[cols_start + 1 : cols_end]
|
|
232
|
+
columns = [c.strip() for c in cols.split(",")]
|
|
233
|
+
|
|
234
|
+
indices.append({
|
|
235
|
+
"name": name,
|
|
236
|
+
"table": table,
|
|
237
|
+
"unique": unique,
|
|
238
|
+
"columns": columns,
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
return indices
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from textwrap import dedent
|
|
4
|
+
from typing import TYPE_CHECKING, TypeVar
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from sqlmodel import SQLModel
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
T = TypeVar("T")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def generate_schema_description(model: type[SQLModel]) -> str:
|
|
15
|
+
"""Generate human-readable schema documentation from SQLModel."""
|
|
16
|
+
table = model.__table__ # type: ignore
|
|
17
|
+
fields: list[str] = []
|
|
18
|
+
|
|
19
|
+
# Get primary keys
|
|
20
|
+
pk_cols = [c.name for c in table.primary_key.columns]
|
|
21
|
+
|
|
22
|
+
# Get field descriptions from model
|
|
23
|
+
docs = {n: f.description for n, f in model.model_fields.items() if f.description}
|
|
24
|
+
# Process each column
|
|
25
|
+
for column in table.columns:
|
|
26
|
+
parts = []
|
|
27
|
+
# Name and type
|
|
28
|
+
parts.append(f"- {column.name}: {column.type}")
|
|
29
|
+
|
|
30
|
+
# Add docstring if available
|
|
31
|
+
if doc := docs.get(column.name):
|
|
32
|
+
parts.append(f"\n Description: {doc}")
|
|
33
|
+
|
|
34
|
+
# Add column properties
|
|
35
|
+
properties = []
|
|
36
|
+
if column.name in pk_cols:
|
|
37
|
+
properties.append("primary key")
|
|
38
|
+
if column.foreign_keys:
|
|
39
|
+
fks = [f"references {fk.column.table.name}" for fk in column.foreign_keys]
|
|
40
|
+
properties.append(f"foreign key ({', '.join(fks)})")
|
|
41
|
+
if not column.nullable:
|
|
42
|
+
properties.append("not null")
|
|
43
|
+
if column.default:
|
|
44
|
+
properties.append(f"default: {column.default.arg}")
|
|
45
|
+
if column.server_default:
|
|
46
|
+
properties.append("has server default")
|
|
47
|
+
if properties:
|
|
48
|
+
parts.append(f" ({', '.join(properties)})")
|
|
49
|
+
|
|
50
|
+
fields.append(" ".join(parts))
|
|
51
|
+
|
|
52
|
+
# Build complete description
|
|
53
|
+
return dedent(f"""
|
|
54
|
+
Table: {table.name}
|
|
55
|
+
Description: {model.__doc__ or "No description available"}
|
|
56
|
+
|
|
57
|
+
Fields:
|
|
58
|
+
{chr(10).join(fields)}
|
|
59
|
+
""")
|
toprompt/to_prompt.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import asyncio
|
|
5
|
+
from collections.abc import Callable, Coroutine
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
import re
|
|
8
|
+
from typing import Any, Literal, Protocol, TypeVar
|
|
9
|
+
|
|
10
|
+
from clinspector import get_cmd_info
|
|
11
|
+
from fieldz import get_adapter
|
|
12
|
+
from llmling import BasePrompt
|
|
13
|
+
from pydantic import BaseModel
|
|
14
|
+
from sqlmodel import SQLModel
|
|
15
|
+
|
|
16
|
+
from toprompt.cli_types import (
|
|
17
|
+
ClickCommandLike,
|
|
18
|
+
TyperCommandLike,
|
|
19
|
+
format_cli_command,
|
|
20
|
+
is_cli_object,
|
|
21
|
+
)
|
|
22
|
+
from toprompt.dataclass_types import format_dataclass_like
|
|
23
|
+
from toprompt.sqlite_types import (
|
|
24
|
+
FileDatabaseLike,
|
|
25
|
+
InMemoryDatabaseLike,
|
|
26
|
+
get_sqlite_schema,
|
|
27
|
+
is_sqlite_db,
|
|
28
|
+
)
|
|
29
|
+
from toprompt.sqlmodel_types import generate_schema_description
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
T = TypeVar("T")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PromptConvertible(Protocol):
|
|
36
|
+
"""Protocol for instances that can be converted to prompts."""
|
|
37
|
+
|
|
38
|
+
def __prompt__(self) -> str: ...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class PromptTypeConvertible(Protocol):
|
|
42
|
+
"""Protocol for types that can be converted to prompts."""
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def __prompt_type__(cls) -> str: ...
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class FieldFormattable(Protocol):
|
|
49
|
+
"""Protocol for types that can be formatted through their fields."""
|
|
50
|
+
|
|
51
|
+
__annotations__: dict[str, Any]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
type AnyPromptType = (
|
|
55
|
+
str
|
|
56
|
+
| PromptConvertible
|
|
57
|
+
| PromptTypeConvertible
|
|
58
|
+
| FieldFormattable
|
|
59
|
+
| BaseModel
|
|
60
|
+
| BasePrompt
|
|
61
|
+
| InMemoryDatabaseLike
|
|
62
|
+
| ClickCommandLike
|
|
63
|
+
| TyperCommandLike
|
|
64
|
+
| argparse.ArgumentParser
|
|
65
|
+
| FileDatabaseLike
|
|
66
|
+
| datetime
|
|
67
|
+
| re.Pattern
|
|
68
|
+
| dict[str, Any]
|
|
69
|
+
| list[Any]
|
|
70
|
+
| tuple[Any, ...]
|
|
71
|
+
| Callable[..., str]
|
|
72
|
+
| Coroutine[Any, Any, str]
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class Template(str): # noqa: SLOT000
|
|
77
|
+
"""Marker class for strings that should be templated."""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
async def to_prompt( # noqa: PLR0911
|
|
81
|
+
obj: AnyPromptType,
|
|
82
|
+
*,
|
|
83
|
+
template_mode: Literal["off", "explicit", "all"] = "off",
|
|
84
|
+
**kwargs: Any,
|
|
85
|
+
) -> str:
|
|
86
|
+
"""Convert any supported type to a prompt string.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
obj: Object to convert
|
|
90
|
+
template_mode: How to handle templating:
|
|
91
|
+
- "off": No templating (default)
|
|
92
|
+
- "explicit": Only Template instances
|
|
93
|
+
- "all": Template all strings (dangerous!)
|
|
94
|
+
**kwargs: Template variables if templating is enabled
|
|
95
|
+
"""
|
|
96
|
+
match obj:
|
|
97
|
+
case Template() if template_mode != "off":
|
|
98
|
+
return render_prompt(obj, kwargs)
|
|
99
|
+
|
|
100
|
+
case str() if template_mode == "all":
|
|
101
|
+
return render_prompt(obj, kwargs)
|
|
102
|
+
|
|
103
|
+
case str():
|
|
104
|
+
return obj
|
|
105
|
+
case type() if hasattr(obj, "__prompt_type__"):
|
|
106
|
+
return obj.__prompt_type__()
|
|
107
|
+
|
|
108
|
+
case _ if hasattr(obj, "__prompt__"):
|
|
109
|
+
return obj.__prompt__() # pyright: ignore[reportAttributeAccessIssue]
|
|
110
|
+
|
|
111
|
+
case datetime():
|
|
112
|
+
return obj.isoformat()
|
|
113
|
+
|
|
114
|
+
case re.Pattern():
|
|
115
|
+
flags = []
|
|
116
|
+
if obj.flags & re.IGNORECASE:
|
|
117
|
+
flags.append("ignorecase")
|
|
118
|
+
if obj.flags & re.MULTILINE:
|
|
119
|
+
flags.append("multiline")
|
|
120
|
+
if obj.flags & re.DOTALL:
|
|
121
|
+
flags.append("dotall")
|
|
122
|
+
if obj.flags & re.VERBOSE:
|
|
123
|
+
flags.append("verbose")
|
|
124
|
+
flags_str = f" ({', '.join(flags)})" if flags else ""
|
|
125
|
+
return f"Pattern: {obj.pattern!r}{flags_str}"
|
|
126
|
+
|
|
127
|
+
case BasePrompt():
|
|
128
|
+
messages = await obj.format(kwargs)
|
|
129
|
+
return "\n".join(msg.get_text_content() for msg in messages)
|
|
130
|
+
|
|
131
|
+
case type() if issubclass(obj, SQLModel): # SQLModel class
|
|
132
|
+
return generate_schema_description(obj)
|
|
133
|
+
|
|
134
|
+
case _ if isinstance(obj, SQLModel): # SQLModel instance
|
|
135
|
+
# Get class documentation first
|
|
136
|
+
schema_doc = generate_schema_description(obj.__class__)
|
|
137
|
+
# Add current values
|
|
138
|
+
values = "\nCurrent Values:\n"
|
|
139
|
+
for field_name, value in obj.__dict__.items():
|
|
140
|
+
if not field_name.startswith("_"):
|
|
141
|
+
values += f"- {field_name}: {value!r}\n"
|
|
142
|
+
return schema_doc + values
|
|
143
|
+
|
|
144
|
+
case _ if is_cli_object(obj):
|
|
145
|
+
cmd_info = get_cmd_info(obj)
|
|
146
|
+
if cmd_info is None:
|
|
147
|
+
msg = f"Could not get CLI info for {type(obj)}"
|
|
148
|
+
raise ValueError(msg)
|
|
149
|
+
return format_cli_command(cmd_info)
|
|
150
|
+
|
|
151
|
+
case _ if can_format_fields(obj):
|
|
152
|
+
return format_dataclass_like(obj)
|
|
153
|
+
case dict():
|
|
154
|
+
results = await asyncio.gather(*(to_prompt(v) for k, v in obj.items()))
|
|
155
|
+
return "\n".join(f"{k}: {r}" for (k, _), r in zip(obj.items(), results))
|
|
156
|
+
|
|
157
|
+
case _ if is_sqlite_db(obj):
|
|
158
|
+
# Pass the connection directly for in-memory databases
|
|
159
|
+
return get_sqlite_schema(obj) # type: ignore
|
|
160
|
+
|
|
161
|
+
case list() | tuple():
|
|
162
|
+
items = await asyncio.gather(*(to_prompt(item) for item in obj))
|
|
163
|
+
return "\n".join(items)
|
|
164
|
+
|
|
165
|
+
case Coroutine():
|
|
166
|
+
result = await obj
|
|
167
|
+
return await to_prompt(result, **kwargs)
|
|
168
|
+
|
|
169
|
+
case _ if callable(obj):
|
|
170
|
+
result = obj()
|
|
171
|
+
return await to_prompt(result, **kwargs)
|
|
172
|
+
|
|
173
|
+
case _:
|
|
174
|
+
return str(obj)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def render_prompt(
|
|
178
|
+
template: str,
|
|
179
|
+
agent_context: dict[str, Any],
|
|
180
|
+
) -> str:
|
|
181
|
+
"""Render a prompt template with context.
|
|
182
|
+
|
|
183
|
+
Available variables:
|
|
184
|
+
agent.name: Name of the agent
|
|
185
|
+
agent.id: Number of the clone (for cloned agents)
|
|
186
|
+
agent.model: Model name
|
|
187
|
+
"""
|
|
188
|
+
from jinja2 import Environment
|
|
189
|
+
|
|
190
|
+
env = Environment(autoescape=True, keep_trailing_newline=True)
|
|
191
|
+
tpl = env.from_string(template)
|
|
192
|
+
return tpl.render(agent=agent_context)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def can_format_fields(obj: Any) -> bool:
|
|
196
|
+
"""Check if object can be inspected by fieldz."""
|
|
197
|
+
try:
|
|
198
|
+
get_adapter(obj)
|
|
199
|
+
except TypeError:
|
|
200
|
+
return False
|
|
201
|
+
else:
|
|
202
|
+
return True
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def format_fastapi_app(app: Any) -> str:
|
|
206
|
+
"""Generate human-readable documentation from FastAPI application."""
|
|
207
|
+
schema = app.openapi()
|
|
208
|
+
lines = ["FastAPI Application Schema:"]
|
|
209
|
+
|
|
210
|
+
# Info section
|
|
211
|
+
if info := schema.get("info", {}):
|
|
212
|
+
if title := info.get("title"):
|
|
213
|
+
lines.append(f"\nTitle: {title}")
|
|
214
|
+
if description := info.get("description"):
|
|
215
|
+
lines.append(f"Description: {description}")
|
|
216
|
+
if version := info.get("version"):
|
|
217
|
+
lines.append(f"Version: {version}")
|
|
218
|
+
|
|
219
|
+
# Endpoints
|
|
220
|
+
lines.append("\nEndpoints:")
|
|
221
|
+
paths = schema.get("paths", {})
|
|
222
|
+
for path, methods in paths.items():
|
|
223
|
+
lines.append(f"\n{path}")
|
|
224
|
+
for method, details in methods.items():
|
|
225
|
+
method_upper = method.upper()
|
|
226
|
+
desc = details.get("description", "No description")
|
|
227
|
+
lines.append(f" {method_upper}: {desc}")
|
|
228
|
+
|
|
229
|
+
# Parameters
|
|
230
|
+
if params := details.get("parameters"):
|
|
231
|
+
lines.append(" Parameters:")
|
|
232
|
+
for param in params:
|
|
233
|
+
req = "*" if param.get("required") else ""
|
|
234
|
+
param_type = param.get("schema", {}).get("type", "any")
|
|
235
|
+
lines.append(
|
|
236
|
+
f" - {param['name']}{req}: {param_type} "
|
|
237
|
+
f"({param.get('description', 'No description')})"
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
# Request body
|
|
241
|
+
if (body := details.get("requestBody")) and (
|
|
242
|
+
ref := (
|
|
243
|
+
body.get("content", {})
|
|
244
|
+
.get("application/json", {})
|
|
245
|
+
.get("schema", {})
|
|
246
|
+
.get("$ref")
|
|
247
|
+
)
|
|
248
|
+
):
|
|
249
|
+
schema_name = ref.split("/")[-1]
|
|
250
|
+
lines.append(f" Request Body: {schema_name}")
|
|
251
|
+
|
|
252
|
+
# Responses
|
|
253
|
+
if responses := details.get("responses"):
|
|
254
|
+
lines.append(" Responses:")
|
|
255
|
+
for status, response in responses.items():
|
|
256
|
+
desc = response.get("description", "No description")
|
|
257
|
+
lines.append(f" {status}: {desc}")
|
|
258
|
+
if ref := (
|
|
259
|
+
response.get("content", {})
|
|
260
|
+
.get("application/json", {})
|
|
261
|
+
.get("schema", {})
|
|
262
|
+
.get("$ref")
|
|
263
|
+
):
|
|
264
|
+
schema_name = ref.split("/")[-1]
|
|
265
|
+
lines.append(f" Schema: {schema_name}")
|
|
266
|
+
|
|
267
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: toprompt
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Convert python objects to LLM-friendly descriptions
|
|
5
|
+
Project-URL: Documentation, https://phil65.github.io/toprompt/
|
|
6
|
+
Project-URL: Source, https://github.com/phil65/toprompt
|
|
7
|
+
Project-URL: Issues, https://github.com/phil65/toprompt/issues
|
|
8
|
+
Project-URL: Discussions, https://github.com/phil65/toprompt/discussions
|
|
9
|
+
Project-URL: Code coverage, https://app.codecov.io/gh/phil65/toprompt
|
|
10
|
+
Author-email: Philipp Temminghoff <philipptemminghoff@googlemail.com>
|
|
11
|
+
License: MIT License
|
|
12
|
+
|
|
13
|
+
Copyright (c) 2024, Philipp Temminghoff
|
|
14
|
+
|
|
15
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
16
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
17
|
+
in the Software without restriction, including without limitation the rights
|
|
18
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
19
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
20
|
+
furnished to do so, subject to the following conditions:
|
|
21
|
+
|
|
22
|
+
The above copyright notice and this permission notice shall be included in all
|
|
23
|
+
copies or substantial portions of the Software.
|
|
24
|
+
|
|
25
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
26
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
27
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
28
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
29
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
30
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
31
|
+
SOFTWARE.
|
|
32
|
+
|
|
33
|
+
License-File: LICENSE
|
|
34
|
+
Classifier: Development Status :: 4 - Beta
|
|
35
|
+
Classifier: Intended Audience :: Developers
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
42
|
+
Classifier: Topic :: Documentation
|
|
43
|
+
Classifier: Topic :: Software Development
|
|
44
|
+
Classifier: Topic :: Utilities
|
|
45
|
+
Classifier: Typing :: Typed
|
|
46
|
+
Requires-Python: >=3.12
|
|
47
|
+
Requires-Dist: clinspector>=0.2.0
|
|
48
|
+
Requires-Dist: jinjarope>=0.16.0
|
|
49
|
+
Requires-Dist: pydantic
|
|
50
|
+
Requires-Dist: sqlmodel>=0.0.22
|
|
51
|
+
Description-Content-Type: text/markdown
|
|
52
|
+
|
|
53
|
+
# ToPrompt
|
|
54
|
+
|
|
55
|
+
[](https://pypi.org/project/toprompt/)
|
|
56
|
+
[](https://pypi.org/project/toprompt/)
|
|
57
|
+
[](https://pypi.org/project/toprompt/)
|
|
58
|
+
[](https://pypi.org/project/toprompt/)
|
|
59
|
+
[](https://pypi.org/project/toprompt/)
|
|
60
|
+
[](https://pypi.org/project/toprompt/)
|
|
61
|
+
[](https://pypi.org/project/toprompt/)
|
|
62
|
+
[](https://pypi.org/project/toprompt/)
|
|
63
|
+
[](https://pypi.org/project/toprompt/)
|
|
64
|
+
[](https://github.com/phil65/toprompt/releases)
|
|
65
|
+
[](https://github.com/phil65/toprompt/graphs/contributors)
|
|
66
|
+
[](https://github.com/phil65/toprompt/discussions)
|
|
67
|
+
[](https://github.com/phil65/toprompt/forks)
|
|
68
|
+
[](https://github.com/phil65/toprompt/issues)
|
|
69
|
+
[](https://github.com/phil65/toprompt/pulls)
|
|
70
|
+
[](https://github.com/phil65/toprompt/watchers)
|
|
71
|
+
[](https://github.com/phil65/toprompt/stars)
|
|
72
|
+
[](https://github.com/phil65/toprompt)
|
|
73
|
+
[](https://github.com/phil65/toprompt/commits)
|
|
74
|
+
[](https://github.com/phil65/toprompt/releases)
|
|
75
|
+
[](https://github.com/phil65/toprompt)
|
|
76
|
+
[](https://github.com/phil65/toprompt)
|
|
77
|
+
[](https://github.com/phil65/toprompt)
|
|
78
|
+
[](https://github.com/phil65/toprompt)
|
|
79
|
+
[](https://codecov.io/gh/phil65/toprompt/)
|
|
80
|
+
[](https://github.com/psf/black)
|
|
81
|
+
[](https://pyup.io/repos/github/phil65/toprompt/)
|
|
82
|
+
|
|
83
|
+
[Read the documentation!](https://phil65.github.io/toprompt/)
|
|
84
|
+
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
toprompt/__init__.py,sha256=TGtKtj-x1gwrBYD98DCPPGtWuB2JSlQw153Anb8DyeE,143
|
|
2
|
+
toprompt/cli_types.py,sha256=lQbxDuMK6mC_b2ArEYurQ1RWdB6DpWjpetHAobD9VHg,4895
|
|
3
|
+
toprompt/dataclass_types.py,sha256=ANb1qq_N0NS6jBYT50azXeVZ2gANkbM4owjpP4mgf9A,858
|
|
4
|
+
toprompt/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
toprompt/sqlite_types.py,sha256=elZLPwidzlhSfRJUS1_XNLV_SMbCsKyz7RO4TWKKzbQ,6353
|
|
6
|
+
toprompt/sqlmodel_types.py,sha256=sd0snSayZEZqUdrj8JR3UTPUDWFoRJ3hzj3Y2Dj1z5k,1847
|
|
7
|
+
toprompt/to_prompt.py,sha256=VW7E7sr9fbat89u1CYoSXnolV9ynt0NZtFlmC2VLh3k,8618
|
|
8
|
+
toprompt-0.0.1.dist-info/METADATA,sha256=DvVv-y7vYzQRbCjaZNrzdR79AYjEBWJNcw2cinmGMsA,5760
|
|
9
|
+
toprompt-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
10
|
+
toprompt-0.0.1.dist-info/licenses/LICENSE,sha256=AteGCH9r177TxxrOFEiOARrastASsf7yW6MQxlAHdwA,1078
|
|
11
|
+
toprompt-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024, Philipp Temminghoff
|
|
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.
|
|
22
|
+
|