mostlyai-mock 0.3.0__tar.gz → 0.3.2__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.
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/PKG-INFO +16 -17
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/README.md +10 -11
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/mostlyai/mock/__init__.py +1 -1
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/mostlyai/mock/core.py +99 -87
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/mostlyai/mock/mcp_server.py +1 -0
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/pyproject.toml +20 -10
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/.gitignore +0 -0
- {mostlyai_mock-0.3.0 → mostlyai_mock-0.3.2}/LICENSE +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: mostlyai-mock
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Synthetic Mock Data
|
|
5
5
|
Project-URL: homepage, https://github.com/mostly-ai/mostlyai-mock
|
|
6
6
|
Project-URL: repository, https://github.com/mostly-ai/mostlyai-mock
|
|
7
|
+
Project-URL: issues, https://github.com/mostly-ai/mostlyai-mock/issues
|
|
7
8
|
Project-URL: documentation, https://mostly-ai.github.io/mostlyai-mock/
|
|
8
|
-
Author-email: MOSTLY AI <dev@mostly.ai>
|
|
9
9
|
License-Expression: Apache-2.0
|
|
10
10
|
License-File: LICENSE
|
|
11
11
|
Classifier: Development Status :: 4 - Beta
|
|
@@ -24,16 +24,16 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
24
24
|
Classifier: Topic :: Software Development :: Libraries
|
|
25
25
|
Classifier: Typing :: Typed
|
|
26
26
|
Requires-Python: >=3.10
|
|
27
|
-
Requires-Dist: litellm>=1.
|
|
27
|
+
Requires-Dist: litellm>=1.83.0
|
|
28
28
|
Requires-Dist: numpy>=1.26.3
|
|
29
29
|
Requires-Dist: pandas>=2.0.0
|
|
30
30
|
Requires-Dist: pyarrow>=14.0.0
|
|
31
31
|
Requires-Dist: pydantic<3.0.0,>=2.0.0
|
|
32
32
|
Requires-Dist: tenacity>=9.1.2
|
|
33
33
|
Provides-Extra: litellm-proxy
|
|
34
|
-
Requires-Dist: litellm[proxy]>=1.
|
|
34
|
+
Requires-Dist: litellm[proxy]>=1.83.0; extra == 'litellm-proxy'
|
|
35
35
|
Provides-Extra: mcp
|
|
36
|
-
Requires-Dist: fastmcp<
|
|
36
|
+
Requires-Dist: fastmcp<4.0.0,>=3.0.0; extra == 'mcp'
|
|
37
37
|
Description-Content-Type: text/markdown
|
|
38
38
|
|
|
39
39
|
# Synthetic Mock Data 🔮
|
|
@@ -64,6 +64,7 @@ pip install -U mostlyai-mock
|
|
|
64
64
|
|
|
65
65
|
```python
|
|
66
66
|
import os
|
|
67
|
+
|
|
67
68
|
os.environ["OPENAI_API_KEY"] = "your-api-key"
|
|
68
69
|
# os.environ["GEMINI_API_KEY"] = "your-api-key"
|
|
69
70
|
# os.environ["GROQ_API_KEY"] = "your-api-key"
|
|
@@ -88,12 +89,12 @@ tables = {
|
|
|
88
89
|
"checkin_time": {"prompt": "the check in timestamp of the guest; may 2025", "dtype": "datetime"},
|
|
89
90
|
"is_vip": {"prompt": "is the guest a VIP", "dtype": "boolean"},
|
|
90
91
|
"price_per_night": {"prompt": "price paid per night, in EUR", "dtype": "float"},
|
|
91
|
-
"room_number": {"prompt": "room number", "dtype": "integer", "values": [101, 102, 103, 201, 202, 203, 204]}
|
|
92
|
+
"room_number": {"prompt": "room number", "dtype": "integer", "values": [101, 102, 103, 201, 202, 203, 204]},
|
|
92
93
|
},
|
|
93
94
|
}
|
|
94
95
|
}
|
|
95
96
|
df = mock.sample(
|
|
96
|
-
tables=tables,
|
|
97
|
+
tables=tables, # provide table and column definitions
|
|
97
98
|
sample_size=10, # generate 10 records
|
|
98
99
|
model="openai/gpt-5-nano", # select the LLM model (optional)
|
|
99
100
|
)
|
|
@@ -265,16 +266,14 @@ tables = {
|
|
|
265
266
|
"primary_key": "guest_id",
|
|
266
267
|
}
|
|
267
268
|
}
|
|
268
|
-
existing_guests = pd.DataFrame(
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
tables=tables,
|
|
275
|
-
existing_data={"guests": existing_guests},
|
|
276
|
-
model="openai/gpt-5-nano"
|
|
269
|
+
existing_guests = pd.DataFrame(
|
|
270
|
+
{
|
|
271
|
+
"guest_id": [1, 2, 3],
|
|
272
|
+
"name": ["Anna Schmidt", "Marco Rossi", "Sophie Dupont"],
|
|
273
|
+
"nationality": ["DE", "IT", "FR"],
|
|
274
|
+
}
|
|
277
275
|
)
|
|
276
|
+
df = mock.sample(tables=tables, existing_data={"guests": existing_guests}, model="openai/gpt-5-nano")
|
|
278
277
|
print(df)
|
|
279
278
|
# guest_id name nationality gender age room_number is_vip
|
|
280
279
|
# 0 1 Anna Schmidt DE female 30 102 False
|
|
@@ -26,6 +26,7 @@ pip install -U mostlyai-mock
|
|
|
26
26
|
|
|
27
27
|
```python
|
|
28
28
|
import os
|
|
29
|
+
|
|
29
30
|
os.environ["OPENAI_API_KEY"] = "your-api-key"
|
|
30
31
|
# os.environ["GEMINI_API_KEY"] = "your-api-key"
|
|
31
32
|
# os.environ["GROQ_API_KEY"] = "your-api-key"
|
|
@@ -50,12 +51,12 @@ tables = {
|
|
|
50
51
|
"checkin_time": {"prompt": "the check in timestamp of the guest; may 2025", "dtype": "datetime"},
|
|
51
52
|
"is_vip": {"prompt": "is the guest a VIP", "dtype": "boolean"},
|
|
52
53
|
"price_per_night": {"prompt": "price paid per night, in EUR", "dtype": "float"},
|
|
53
|
-
"room_number": {"prompt": "room number", "dtype": "integer", "values": [101, 102, 103, 201, 202, 203, 204]}
|
|
54
|
+
"room_number": {"prompt": "room number", "dtype": "integer", "values": [101, 102, 103, 201, 202, 203, 204]},
|
|
54
55
|
},
|
|
55
56
|
}
|
|
56
57
|
}
|
|
57
58
|
df = mock.sample(
|
|
58
|
-
tables=tables,
|
|
59
|
+
tables=tables, # provide table and column definitions
|
|
59
60
|
sample_size=10, # generate 10 records
|
|
60
61
|
model="openai/gpt-5-nano", # select the LLM model (optional)
|
|
61
62
|
)
|
|
@@ -227,16 +228,14 @@ tables = {
|
|
|
227
228
|
"primary_key": "guest_id",
|
|
228
229
|
}
|
|
229
230
|
}
|
|
230
|
-
existing_guests = pd.DataFrame(
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
tables=tables,
|
|
237
|
-
existing_data={"guests": existing_guests},
|
|
238
|
-
model="openai/gpt-5-nano"
|
|
231
|
+
existing_guests = pd.DataFrame(
|
|
232
|
+
{
|
|
233
|
+
"guest_id": [1, 2, 3],
|
|
234
|
+
"name": ["Anna Schmidt", "Marco Rossi", "Sophie Dupont"],
|
|
235
|
+
"nationality": ["DE", "IT", "FR"],
|
|
236
|
+
}
|
|
239
237
|
)
|
|
238
|
+
df = mock.sample(tables=tables, existing_data={"guests": existing_guests}, model="openai/gpt-5-nano")
|
|
240
239
|
print(df)
|
|
241
240
|
# guest_id name nationality gender age room_number is_vip
|
|
242
241
|
# 0 1 Anna Schmidt DE female 30 102 False
|
|
@@ -18,6 +18,7 @@ import asyncio
|
|
|
18
18
|
import concurrent.futures
|
|
19
19
|
import json
|
|
20
20
|
import math
|
|
21
|
+
import re
|
|
21
22
|
import time
|
|
22
23
|
from collections import deque
|
|
23
24
|
from collections.abc import AsyncGenerator, Awaitable, Callable
|
|
@@ -44,7 +45,26 @@ class LLMConfig(BaseModel):
|
|
|
44
45
|
api_key: str | None
|
|
45
46
|
api_base: str | None
|
|
46
47
|
temperature: float
|
|
47
|
-
top_p: float
|
|
48
|
+
top_p: float | None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _reasoning_effort(model: str) -> str | None:
|
|
52
|
+
"""Pick the lowest reasoning effort for OpenAI reasoning models; None for all other models."""
|
|
53
|
+
model_only = model.split("/")[-1]
|
|
54
|
+
if re.fullmatch(r"o\d+(-.*)?", model_only):
|
|
55
|
+
return "low"
|
|
56
|
+
match = re.match(r"gpt-(\d+)", model_only)
|
|
57
|
+
if match and int(match.group(1)) >= 5:
|
|
58
|
+
# newer models (e.g. gpt-5.4+, gpt-6-luna) accept "none" but reject "minimal"
|
|
59
|
+
model_info = litellm.model_cost.get(model) or litellm.model_cost.get(model_only) or {}
|
|
60
|
+
return "none" if model_info.get("supports_none_reasoning_effort") else "minimal"
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _supports_top_p(model: str, reasoning_effort: str | None) -> bool:
|
|
65
|
+
"""OpenAI reasoning models and Anthropic Claude models reject top_p."""
|
|
66
|
+
model_only = model.split("/")[-1]
|
|
67
|
+
return reasoning_effort is None and not model_only.startswith("claude")
|
|
48
68
|
|
|
49
69
|
|
|
50
70
|
class MockConfig(RootModel[dict[str, "TableConfig"]]):
|
|
@@ -136,9 +156,9 @@ class MockConfig(RootModel[dict[str, "TableConfig"]]):
|
|
|
136
156
|
)
|
|
137
157
|
return self
|
|
138
158
|
|
|
139
|
-
def get_dependency_mappings(self) -> tuple[dict[str,
|
|
140
|
-
child_to_parents = {}
|
|
141
|
-
parent_to_children = {}
|
|
159
|
+
def get_dependency_mappings(self) -> tuple[dict[str, set[str]], dict[str, set[str]], list[str]]:
|
|
160
|
+
child_to_parents: dict[str, set[str]] = {}
|
|
161
|
+
parent_to_children: dict[str, set[str]] = {}
|
|
142
162
|
|
|
143
163
|
for table_name in self.root:
|
|
144
164
|
child_to_parents[table_name] = set()
|
|
@@ -172,19 +192,17 @@ class ColumnConfig(BaseModel):
|
|
|
172
192
|
|
|
173
193
|
@model_validator(mode="before")
|
|
174
194
|
def set_default_dtype(cls, data):
|
|
175
|
-
if isinstance(data, dict):
|
|
176
|
-
if "
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
data["dtype"] = DType.STRING
|
|
195
|
+
if isinstance(data, dict) and "dtype" not in data:
|
|
196
|
+
if data.get("values"):
|
|
197
|
+
data["dtype"] = DType.CATEGORY
|
|
198
|
+
else:
|
|
199
|
+
data["dtype"] = DType.STRING
|
|
181
200
|
return data
|
|
182
201
|
|
|
183
202
|
@model_validator(mode="after")
|
|
184
203
|
def ensure_values_are_unique(self) -> ColumnConfig:
|
|
185
|
-
if self.values:
|
|
186
|
-
|
|
187
|
-
raise ValueError("Values must be unique")
|
|
204
|
+
if self.values and len(self.values) != len(set(self.values)):
|
|
205
|
+
raise ValueError("Values must be unique")
|
|
188
206
|
return self
|
|
189
207
|
|
|
190
208
|
@model_validator(mode="after")
|
|
@@ -242,7 +260,7 @@ async def _sample_table(
|
|
|
242
260
|
prompt: str,
|
|
243
261
|
columns: dict[str, ColumnConfig],
|
|
244
262
|
foreign_keys: list[ForeignKeyConfig],
|
|
245
|
-
primary_keys: dict[str, str],
|
|
263
|
+
primary_keys: dict[str, str | None],
|
|
246
264
|
data: dict[str, pd.DataFrame],
|
|
247
265
|
sample_size: int | None,
|
|
248
266
|
previous_rows_size: int,
|
|
@@ -251,7 +269,7 @@ async def _sample_table(
|
|
|
251
269
|
llm_config: LLMConfig,
|
|
252
270
|
config: MockConfig,
|
|
253
271
|
progress_callback: Callable[..., Awaitable[None]] | None = None,
|
|
254
|
-
batch_size
|
|
272
|
+
batch_size=None,
|
|
255
273
|
) -> pd.DataFrame:
|
|
256
274
|
# provide a default progress callback if none is provided
|
|
257
275
|
if progress_callback is None:
|
|
@@ -323,7 +341,7 @@ def _create_table_prompt(
|
|
|
323
341
|
name: str,
|
|
324
342
|
prompt: str,
|
|
325
343
|
columns: dict[str, ColumnConfig],
|
|
326
|
-
primary_keys: dict[str, str],
|
|
344
|
+
primary_keys: dict[str, str | None],
|
|
327
345
|
batch_idx: int,
|
|
328
346
|
batch_size: int | None,
|
|
329
347
|
foreign_keys: list[ForeignKeyConfig],
|
|
@@ -354,14 +372,16 @@ def _create_table_prompt(
|
|
|
354
372
|
column: spec for column, spec in column_specifications.items() if column not in existing_data.columns
|
|
355
373
|
}
|
|
356
374
|
# ensure primary keys stay as string in the prompt, even if dtype is integer
|
|
357
|
-
if
|
|
358
|
-
|
|
359
|
-
|
|
375
|
+
if (
|
|
376
|
+
target_primary_key
|
|
377
|
+
and target_primary_key in column_specifications
|
|
378
|
+
and columns[target_primary_key].dtype == DType.INTEGER
|
|
379
|
+
):
|
|
380
|
+
column_specifications[target_primary_key]["dtype"] = DType.STRING.value
|
|
360
381
|
# ensure foreign keys referencing integer primary keys also stay as string in the prompt
|
|
361
382
|
for fk in foreign_keys:
|
|
362
|
-
if fk.column in column_specifications:
|
|
363
|
-
|
|
364
|
-
column_specifications[fk.column]["dtype"] = DType.STRING.value
|
|
383
|
+
if fk.column in column_specifications and columns[fk.column].dtype == DType.INTEGER:
|
|
384
|
+
column_specifications[fk.column]["dtype"] = DType.STRING.value
|
|
365
385
|
prompt += f"{json.dumps(column_specifications, indent=2)}\n\n"
|
|
366
386
|
|
|
367
387
|
# add previous rows as context to help the LLM generate consistent data
|
|
@@ -446,7 +466,6 @@ def _create_table_prompt(
|
|
|
446
466
|
if n_rows is not None:
|
|
447
467
|
prompt += f"Number of data rows to {verb}: `{n_rows}`.\n\n"
|
|
448
468
|
|
|
449
|
-
|
|
450
469
|
if target_primary_key is not None:
|
|
451
470
|
prompt += f"Add prefix to all values of Target Table Primary Key. The prefix is 'B{batch_idx}-'."
|
|
452
471
|
prompt += " There is one exception: if primary keys are in existing data, don't add prefix to them."
|
|
@@ -506,7 +525,7 @@ def _create_table_prompt(
|
|
|
506
525
|
if existing_data is not None:
|
|
507
526
|
prompt += f" Only include the following columns in the {llm_output_format.value} string: {list(columns.keys() - existing_data.columns)}."
|
|
508
527
|
|
|
509
|
-
if llm_output_format == LLMOutputFormat.CSV and batch_size > 10:
|
|
528
|
+
if llm_output_format == LLMOutputFormat.CSV and batch_size is not None and batch_size > 10:
|
|
510
529
|
prompt += " Additionally, add column called `_ROW_IDX` that is a counter from 1 to the number of rows generated so far within current batch."
|
|
511
530
|
|
|
512
531
|
prompt += "\n"
|
|
@@ -547,18 +566,18 @@ async def _yield_rows_from_json_chunks_stream(response: litellm.CustomStreamWrap
|
|
|
547
566
|
elif char == "{" and not in_row_json:
|
|
548
567
|
# {"rows": [{"name": "Jo\}h\{n"}]}
|
|
549
568
|
# * <- start of single row json stream
|
|
550
|
-
buffer =
|
|
569
|
+
buffer = ["{"]
|
|
551
570
|
in_row_json = True
|
|
552
571
|
elif char == "}":
|
|
553
572
|
# {"rows": [{"name": "Jo\}h\{n"}]}
|
|
554
573
|
# * * * <- any of these
|
|
555
574
|
try:
|
|
556
575
|
row = buffer_to_row(buffer)
|
|
557
|
-
except Exception:
|
|
576
|
+
except Exception: # noqa: BLE001, S112
|
|
558
577
|
# in case of any error, silently drop the row
|
|
559
578
|
continue
|
|
560
579
|
finally:
|
|
561
|
-
buffer =
|
|
580
|
+
buffer = []
|
|
562
581
|
in_row_json = False
|
|
563
582
|
yield row
|
|
564
583
|
|
|
@@ -567,8 +586,8 @@ async def _yield_rows_from_csv_chunks_stream(response: litellm.CustomStreamWrapp
|
|
|
567
586
|
def buffer_to_row(buffer: list[str]) -> list[str]:
|
|
568
587
|
return pd.read_csv(StringIO("".join(buffer)), header=None).astype(str).iloc[0].to_list()
|
|
569
588
|
|
|
570
|
-
buffer =
|
|
571
|
-
header = None
|
|
589
|
+
buffer = []
|
|
590
|
+
header: list[str] | None = None
|
|
572
591
|
async for chunk in response:
|
|
573
592
|
delta = chunk.choices[0].delta.content
|
|
574
593
|
if delta is None:
|
|
@@ -578,11 +597,11 @@ async def _yield_rows_from_csv_chunks_stream(response: litellm.CustomStreamWrapp
|
|
|
578
597
|
if char == "\n":
|
|
579
598
|
try:
|
|
580
599
|
row = buffer_to_row(buffer)
|
|
581
|
-
except Exception:
|
|
600
|
+
except Exception: # noqa: BLE001, S112
|
|
582
601
|
# in case of any error, silently drop the row
|
|
583
602
|
continue
|
|
584
603
|
finally:
|
|
585
|
-
buffer =
|
|
604
|
+
buffer = []
|
|
586
605
|
if header is None:
|
|
587
606
|
# column1,column2,column3\n
|
|
588
607
|
# ** <- end of header row
|
|
@@ -591,12 +610,12 @@ async def _yield_rows_from_csv_chunks_stream(response: litellm.CustomStreamWrapp
|
|
|
591
610
|
# value_1,value_2,value_3\n
|
|
592
611
|
# ** <- end of data row
|
|
593
612
|
yield dict(zip(header, row))
|
|
594
|
-
if buffer:
|
|
613
|
+
if buffer and header is not None:
|
|
595
614
|
# last row might not finish with a newline, in which case the buffer would not be empty here
|
|
596
615
|
try:
|
|
597
616
|
last_row = buffer_to_row(buffer)
|
|
598
617
|
yield dict(zip(header, last_row))
|
|
599
|
-
except Exception:
|
|
618
|
+
except Exception: # noqa: BLE001, S110
|
|
600
619
|
# in case of any error, silently drop the row
|
|
601
620
|
pass
|
|
602
621
|
|
|
@@ -607,7 +626,7 @@ def _create_structured_output_schema(
|
|
|
607
626
|
primary_key: str | None,
|
|
608
627
|
foreign_keys: list[ForeignKeyConfig],
|
|
609
628
|
) -> type[BaseModel]:
|
|
610
|
-
def create_annotation(column_config: ColumnConfig, is_int_pk_or_fk: bool = False) ->
|
|
629
|
+
def create_annotation(column_config: ColumnConfig, is_int_pk_or_fk: bool = False) -> Any:
|
|
611
630
|
if column_config.values or column_config.dtype is DType.CATEGORY:
|
|
612
631
|
return Literal[tuple(column_config.values)] # type: ignore
|
|
613
632
|
# ensure integer primary keys and foreign keys are treated as strings
|
|
@@ -628,11 +647,11 @@ def _create_structured_output_schema(
|
|
|
628
647
|
for column_name, column_config in columns.items():
|
|
629
648
|
if existing_data is not None and column_name in existing_data.columns:
|
|
630
649
|
continue # skip columns that already exist in existing data
|
|
631
|
-
is_int_pk = primary_key and column_name == primary_key and column_config.dtype == DType.INTEGER
|
|
650
|
+
is_int_pk = primary_key is not None and column_name == primary_key and column_config.dtype == DType.INTEGER
|
|
632
651
|
is_int_fk = any(fk.column == column_name for fk in foreign_keys) and column_config.dtype == DType.INTEGER
|
|
633
652
|
annotation = create_annotation(column_config, is_int_pk or is_int_fk)
|
|
634
653
|
fields[column_name] = (annotation, Field(...))
|
|
635
|
-
TableRow = create_model("TableRow", **fields)
|
|
654
|
+
TableRow = create_model("TableRow", **fields) # ty: ignore[no-matching-overload]
|
|
636
655
|
TableRows = create_model("TableRows", rows=(list[TableRow], ...))
|
|
637
656
|
return TableRows
|
|
638
657
|
|
|
@@ -643,7 +662,7 @@ async def _worker(
|
|
|
643
662
|
prompt: str,
|
|
644
663
|
columns: dict[str, ColumnConfig],
|
|
645
664
|
foreign_keys: list[ForeignKeyConfig],
|
|
646
|
-
primary_keys: dict[str, str],
|
|
665
|
+
primary_keys: dict[str, str | None],
|
|
647
666
|
previous_rows: deque[dict],
|
|
648
667
|
batch_queue: asyncio.Queue,
|
|
649
668
|
result_queue: asyncio.Queue,
|
|
@@ -692,23 +711,11 @@ async def _worker(
|
|
|
692
711
|
"stream": True,
|
|
693
712
|
}
|
|
694
713
|
|
|
695
|
-
|
|
696
|
-
model_only = llm_config.model.split("/")[-1] if "/" in llm_config.model else llm_config.model
|
|
697
|
-
reasoning_effort = (
|
|
698
|
-
"low"
|
|
699
|
-
if (model_only.startswith("o") and (model_only[1:].isdigit() or model_only[1:].split("-")[0].isdigit()))
|
|
700
|
-
else "minimal"
|
|
701
|
-
if (
|
|
702
|
-
model_only.startswith("gpt-")
|
|
703
|
-
and model_only.split("-")[1].isdigit()
|
|
704
|
-
and int(model_only.split("-")[1]) >= 5
|
|
705
|
-
)
|
|
706
|
-
else None
|
|
707
|
-
)
|
|
708
|
-
|
|
714
|
+
reasoning_effort = _reasoning_effort(llm_config.model)
|
|
709
715
|
if reasoning_effort:
|
|
710
|
-
litellm_kwargs.pop("top_p")
|
|
711
716
|
litellm_kwargs["reasoning_effort"] = reasoning_effort
|
|
717
|
+
if llm_config.top_p is None or not _supports_top_p(llm_config.model, reasoning_effort):
|
|
718
|
+
litellm_kwargs.pop("top_p")
|
|
712
719
|
|
|
713
720
|
# construct messages
|
|
714
721
|
system_prompt = _create_system_prompt(llm_output_format)
|
|
@@ -798,7 +805,7 @@ async def _worker(
|
|
|
798
805
|
row_existing_part = existing_batch.iloc[row_idx].to_dict() if existing_batch is not None else {}
|
|
799
806
|
row = {**row_generated_part, **row_existing_part}
|
|
800
807
|
# keep columns order according to user's spec
|
|
801
|
-
row = {column: row[column] for column in columns
|
|
808
|
+
row = {column: row[column] for column in columns}
|
|
802
809
|
rows.append(row)
|
|
803
810
|
|
|
804
811
|
# track previous rows for improved data consistency, in case of sequential generation
|
|
@@ -820,7 +827,7 @@ async def _create_table_rows_generator(
|
|
|
820
827
|
prompt: str,
|
|
821
828
|
columns: dict[str, ColumnConfig],
|
|
822
829
|
foreign_keys: list[ForeignKeyConfig],
|
|
823
|
-
primary_keys: dict[str, str],
|
|
830
|
+
primary_keys: dict[str, str | None],
|
|
824
831
|
data: dict[str, pd.DataFrame],
|
|
825
832
|
sample_size: int | None,
|
|
826
833
|
previous_rows_size: int,
|
|
@@ -828,9 +835,8 @@ async def _create_table_rows_generator(
|
|
|
828
835
|
n_workers: int,
|
|
829
836
|
llm_config: LLMConfig,
|
|
830
837
|
progress_callback: Callable[..., Awaitable[None]] | None = None,
|
|
831
|
-
batch_size: int | None = 20,
|
|
832
|
-
) -> AsyncGenerator[dict]:
|
|
833
|
-
|
|
838
|
+
batch_size: int | None = 20, # generate 20 root table rows at a time
|
|
839
|
+
) -> AsyncGenerator[tuple[int, dict]]:
|
|
834
840
|
def supports_structured_outputs(model: str) -> bool:
|
|
835
841
|
model = model.removeprefix("litellm_proxy/")
|
|
836
842
|
supported_params = litellm.get_supported_openai_params(model=model) or []
|
|
@@ -838,6 +844,10 @@ async def _create_table_rows_generator(
|
|
|
838
844
|
|
|
839
845
|
llm_output_format = LLMOutputFormat.JSON if supports_structured_outputs(llm_config.model) else LLMOutputFormat.CSV
|
|
840
846
|
|
|
847
|
+
# Callers pass batch_size=None explicitly; that overrides the parameter default unless normalized here.
|
|
848
|
+
if batch_size is None:
|
|
849
|
+
batch_size = 20
|
|
850
|
+
|
|
841
851
|
previous_rows = deque(maxlen=previous_rows_size)
|
|
842
852
|
|
|
843
853
|
# derive data for augmentation
|
|
@@ -870,11 +880,11 @@ async def _create_table_rows_generator(
|
|
|
870
880
|
non_context_data[non_context_table_name] = data[non_context_table_name]
|
|
871
881
|
|
|
872
882
|
# calculate ideal batch size that spreads the workload evenly across workers
|
|
883
|
+
assert sample_size is not None
|
|
873
884
|
ideal_batch_size = max(math.ceil(sample_size / n_workers), 5)
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
batch_size = ideal_batch_size
|
|
885
|
+
# never increase batch_size beyond initial value
|
|
886
|
+
# this is especially important for sequential tables, where batch_size is currently assumed to be 1 everywhere
|
|
887
|
+
batch_size = min(batch_size, ideal_batch_size)
|
|
878
888
|
|
|
879
889
|
# calculate batch_sizes
|
|
880
890
|
assert sample_size is not None, "sample_size should have been filled by this point"
|
|
@@ -918,7 +928,7 @@ async def _create_table_rows_generator(
|
|
|
918
928
|
non_context_batch: dict[str, pd.DataFrame] | None = None
|
|
919
929
|
if non_context_data:
|
|
920
930
|
non_context_batch = {
|
|
921
|
-
table_name: df.sample(frac=1.0).
|
|
931
|
+
table_name: df.sample(frac=1.0).iloc[:non_context_size] for table_name, df in non_context_data.items()
|
|
922
932
|
}
|
|
923
933
|
|
|
924
934
|
task = {
|
|
@@ -1012,7 +1022,7 @@ def _align_series_dtypes_with_column_config(series: pd.Series, column_config: Co
|
|
|
1012
1022
|
def harmonize_datetime(x: Any):
|
|
1013
1023
|
try:
|
|
1014
1024
|
return dateutil.parser.parse(str(x))
|
|
1015
|
-
except Exception:
|
|
1025
|
+
except Exception: # noqa: BLE001
|
|
1016
1026
|
return pd.NaT
|
|
1017
1027
|
|
|
1018
1028
|
series = pd.to_datetime(series.apply(harmonize_datetime), errors="coerce")
|
|
@@ -1025,7 +1035,7 @@ def _align_series_dtypes_with_column_config(series: pd.Series, column_config: Co
|
|
|
1025
1035
|
series = series.map(lambda x: False if str(x).lower() == "false" else x)
|
|
1026
1036
|
series = pd.to_numeric(series, errors="coerce").astype("boolean[pyarrow]")
|
|
1027
1037
|
elif column_config.dtype is DType.CATEGORY:
|
|
1028
|
-
series = pd.Categorical(series, categories=column_config.values)
|
|
1038
|
+
series = pd.Series(pd.Categorical(series, categories=column_config.values), index=series.index)
|
|
1029
1039
|
else:
|
|
1030
1040
|
series = series.astype("string[pyarrow]")
|
|
1031
1041
|
return series
|
|
@@ -1054,7 +1064,7 @@ def _get_integer_pk_fk_columns(
|
|
|
1054
1064
|
|
|
1055
1065
|
|
|
1056
1066
|
async def _convert_table_rows_generator_to_df(
|
|
1057
|
-
table_rows_generator: AsyncGenerator[dict],
|
|
1067
|
+
table_rows_generator: AsyncGenerator[tuple[int, dict]],
|
|
1058
1068
|
columns: dict[str, ColumnConfig],
|
|
1059
1069
|
primary_key: str | None = None,
|
|
1060
1070
|
foreign_keys: list[ForeignKeyConfig] | None = None,
|
|
@@ -1075,11 +1085,11 @@ async def _convert_table_rows_generator_to_df(
|
|
|
1075
1085
|
return df
|
|
1076
1086
|
|
|
1077
1087
|
# consume entire generator
|
|
1078
|
-
items = [
|
|
1088
|
+
items = [(batch_idx, row) async for batch_idx, row in table_rows_generator]
|
|
1079
1089
|
# sort items by batch_idx to maintain order (relevant especially for keeping the order of existing data)
|
|
1080
|
-
items = sorted(items, key=lambda x: x[
|
|
1090
|
+
items = sorted(items, key=lambda x: x[0])
|
|
1081
1091
|
# extract rows and convert to DataFrame
|
|
1082
|
-
rows = [
|
|
1092
|
+
rows = [row for _, row in items]
|
|
1083
1093
|
df = pd.DataFrame(rows)
|
|
1084
1094
|
# harmonize dtypes
|
|
1085
1095
|
df = align_df_dtypes_with_mock_dtypes(df, columns)
|
|
@@ -1162,12 +1172,13 @@ def _harmonize_existing_data(
|
|
|
1162
1172
|
)
|
|
1163
1173
|
|
|
1164
1174
|
# ensure that the existing data has values allowed by the column config
|
|
1165
|
-
if existing_column_config.values
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1175
|
+
if existing_column_config.values and not set(existing_table[existing_column].unique()).issubset(
|
|
1176
|
+
existing_column_config.values
|
|
1177
|
+
):
|
|
1178
|
+
raise ValueError(
|
|
1179
|
+
f"Existing data column '{existing_column}' in table '{existing_table_name}' has values disallowed by the column config. "
|
|
1180
|
+
f"Ensure that the existing data is consistent with the mock configuration."
|
|
1181
|
+
)
|
|
1171
1182
|
|
|
1172
1183
|
# ensure that the existing data has unique primary keys
|
|
1173
1184
|
existing_table_primary_key = existing_table_config.primary_key
|
|
@@ -1247,7 +1258,9 @@ def _postprocess_table(
|
|
|
1247
1258
|
# map FK values from strings to integers
|
|
1248
1259
|
mapping = pk_mappings[fk.referenced_table]
|
|
1249
1260
|
df[fk.column] = (
|
|
1250
|
-
df[fk.column]
|
|
1261
|
+
df[fk.column]
|
|
1262
|
+
.apply(lambda val, mapping=mapping: mapping.get(str(val)) if pd.notna(val) else None)
|
|
1263
|
+
.astype("int64[pyarrow]")
|
|
1251
1264
|
)
|
|
1252
1265
|
|
|
1253
1266
|
return df
|
|
@@ -1262,14 +1275,13 @@ async def _sample_common(
|
|
|
1262
1275
|
api_key: str | None = None,
|
|
1263
1276
|
api_base: str | None = None,
|
|
1264
1277
|
temperature: float = 1.0,
|
|
1265
|
-
top_p: float = 0.95,
|
|
1278
|
+
top_p: float | None = 0.95,
|
|
1266
1279
|
n_workers: int = 10,
|
|
1267
1280
|
return_type: Literal["auto", "dict"] = "auto",
|
|
1268
1281
|
progress_callback: Callable[..., Awaitable[None]] | None = None,
|
|
1269
|
-
batch_size: int | None = None
|
|
1282
|
+
batch_size: int | None = None,
|
|
1270
1283
|
):
|
|
1271
|
-
|
|
1272
|
-
config = MockConfig(tables)
|
|
1284
|
+
config = MockConfig(_harmonize_tables(tables, existing_data))
|
|
1273
1285
|
|
|
1274
1286
|
llm_config = LLMConfig(model=model, api_key=api_key, api_base=api_base, temperature=temperature, top_p=top_p)
|
|
1275
1287
|
|
|
@@ -1302,7 +1314,7 @@ async def _sample_common(
|
|
|
1302
1314
|
llm_config=llm_config,
|
|
1303
1315
|
config=config,
|
|
1304
1316
|
progress_callback=progress_callback,
|
|
1305
|
-
batch_size=batch_size
|
|
1317
|
+
batch_size=batch_size,
|
|
1306
1318
|
)
|
|
1307
1319
|
data[table_name] = df
|
|
1308
1320
|
|
|
@@ -1323,11 +1335,11 @@ def sample(
|
|
|
1323
1335
|
api_key: str | None = None,
|
|
1324
1336
|
api_base: str | None = None,
|
|
1325
1337
|
temperature: float = 1.0,
|
|
1326
|
-
top_p: float = 0.95,
|
|
1338
|
+
top_p: float | None = 0.95,
|
|
1327
1339
|
n_workers: int = 10,
|
|
1328
1340
|
return_type: Literal["auto", "dict"] = "auto",
|
|
1329
1341
|
progress_callback: Callable[..., Awaitable[None]] | None = None,
|
|
1330
|
-
batch_size: int | None = None
|
|
1342
|
+
batch_size: int | None = None,
|
|
1331
1343
|
) -> pd.DataFrame | dict[str, pd.DataFrame]:
|
|
1332
1344
|
"""
|
|
1333
1345
|
Generate synthetic data from scratch or enrich existing data with new columns.
|
|
@@ -1366,7 +1378,7 @@ def sample(
|
|
|
1366
1378
|
api_key (str | None): The API key to use for the LLM. If not provided, LiteLLM will take it from the environment variables.
|
|
1367
1379
|
api_base (str | None): Override the API base URL. Useful for OpenAI-compatible self-hosted endpoints. If not provided, LiteLLM uses the default endpoint for the chosen model.
|
|
1368
1380
|
temperature (float): The temperature to use for the LLM. Default is 1.0.
|
|
1369
|
-
top_p (float): The top-p value to use for the LLM. Default is 0.95.
|
|
1381
|
+
top_p (float | None): The top-p value to use for the LLM. Default is 0.95. Ignored for models that reject it (OpenAI reasoning models, Anthropic Claude); pass None to never send it.
|
|
1370
1382
|
n_workers (int): The number of concurrent workers making the LLM calls. Default is 10. The value is clamped to the range [1, 10].
|
|
1371
1383
|
If n_workers is 1, the generation of batches becomes sequential and certain features for better data consistency are enabled.
|
|
1372
1384
|
return_type (Literal["auto", "dict"]): The format of the returned data. Default is "auto".
|
|
@@ -1617,7 +1629,7 @@ def sample(
|
|
|
1617
1629
|
n_workers=n_workers,
|
|
1618
1630
|
return_type=return_type,
|
|
1619
1631
|
progress_callback=progress_callback,
|
|
1620
|
-
batch_size=batch_size
|
|
1632
|
+
batch_size=batch_size,
|
|
1621
1633
|
)
|
|
1622
1634
|
return future.result()
|
|
1623
1635
|
|
|
@@ -1631,11 +1643,11 @@ async def _asample(
|
|
|
1631
1643
|
api_key: str | None = None,
|
|
1632
1644
|
api_base: str | None = None,
|
|
1633
1645
|
temperature: float = 1.0,
|
|
1634
|
-
top_p: float = 0.95,
|
|
1646
|
+
top_p: float | None = 0.95,
|
|
1635
1647
|
n_workers: int = 10,
|
|
1636
1648
|
return_type: Literal["auto", "dict"] = "auto",
|
|
1637
1649
|
progress_callback: Callable[..., Awaitable[None]] | None = None,
|
|
1638
|
-
batch_size: int | None = None
|
|
1650
|
+
batch_size: int | None = None,
|
|
1639
1651
|
) -> pd.DataFrame | dict[str, pd.DataFrame]:
|
|
1640
1652
|
return await _sample_common(
|
|
1641
1653
|
tables=tables,
|
|
@@ -1649,7 +1661,7 @@ async def _asample(
|
|
|
1649
1661
|
n_workers=n_workers,
|
|
1650
1662
|
return_type=return_type,
|
|
1651
1663
|
progress_callback=progress_callback,
|
|
1652
|
-
batch_size=batch_size
|
|
1664
|
+
batch_size=batch_size,
|
|
1653
1665
|
)
|
|
1654
1666
|
|
|
1655
1667
|
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "mostlyai-mock"
|
|
3
|
-
version = "0.3.
|
|
3
|
+
version = "0.3.2"
|
|
4
4
|
description = "Synthetic Mock Data"
|
|
5
|
-
authors = [{ name = "MOSTLY AI", email = "dev@mostly.ai" }]
|
|
6
5
|
requires-python = ">=3.10"
|
|
7
6
|
readme = "README.md"
|
|
8
7
|
license = "Apache-2.0"
|
|
@@ -28,34 +27,37 @@ dependencies = [
|
|
|
28
27
|
"numpy>=1.26.3",
|
|
29
28
|
"pandas>=2.0.0",
|
|
30
29
|
"pyarrow>=14.0.0",
|
|
31
|
-
"litellm>=1.
|
|
30
|
+
"litellm>=1.83.0",
|
|
32
31
|
"tenacity>=9.1.2",
|
|
33
32
|
]
|
|
34
33
|
|
|
35
34
|
[project.optional-dependencies]
|
|
36
35
|
litellm-proxy = [
|
|
37
|
-
"litellm[proxy]>=1.
|
|
36
|
+
"litellm[proxy]>=1.83.0",
|
|
38
37
|
]
|
|
39
38
|
mcp = [
|
|
40
|
-
"fastmcp>=
|
|
39
|
+
"fastmcp>=3.0.0,<4.0.0",
|
|
41
40
|
]
|
|
42
41
|
|
|
43
42
|
[dependency-groups]
|
|
44
43
|
dev = [
|
|
45
44
|
"pytest>=8.0",
|
|
46
|
-
"ruff>=0.
|
|
47
|
-
"
|
|
45
|
+
"ruff>=0.17", # sync'ed with .pre-commit-config
|
|
46
|
+
"prek>=0.5.12",
|
|
47
|
+
"ty==0.0.112", # pinned: ty is pre-1.0 and diagnostics change between releases
|
|
48
48
|
"twine>=6.1",
|
|
49
49
|
"ipykernel>=6.25",
|
|
50
50
|
]
|
|
51
51
|
docs = [
|
|
52
52
|
"mkdocs>=1.6",
|
|
53
53
|
"mkdocstrings[crystal, python]>=0.29",
|
|
54
|
+
# mkdocstrings-python 2.x expects griffe 2 / griffelib; handler still imports legacy `griffe` API.
|
|
55
|
+
"mkdocstrings-python>=1.16.2,<2",
|
|
54
56
|
"mkdocs-material>=9.0",
|
|
55
57
|
"mkdocs-llmstxt>=0.2",
|
|
56
|
-
"griffe>=1.
|
|
58
|
+
"griffe>=1.13,<2",
|
|
57
59
|
"pymdown-extensions>=10.0",
|
|
58
|
-
"griffe-fieldz>=0.2",
|
|
60
|
+
"griffe-fieldz>=0.2,<0.5",
|
|
59
61
|
"black>=25.0",
|
|
60
62
|
]
|
|
61
63
|
|
|
@@ -65,6 +67,7 @@ mcp-server = "mostlyai.mock.mcp_server:main"
|
|
|
65
67
|
[project.urls]
|
|
66
68
|
homepage = "https://github.com/mostly-ai/mostlyai-mock"
|
|
67
69
|
repository = "https://github.com/mostly-ai/mostlyai-mock"
|
|
70
|
+
issues = "https://github.com/mostly-ai/mostlyai-mock/issues"
|
|
68
71
|
documentation = "https://mostly-ai.github.io/mostlyai-mock/"
|
|
69
72
|
|
|
70
73
|
[tool.uv]
|
|
@@ -92,4 +95,11 @@ target-version = "py310"
|
|
|
92
95
|
line-length = 120
|
|
93
96
|
|
|
94
97
|
[tool.ruff.lint]
|
|
95
|
-
extend-select = ["I"]
|
|
98
|
+
extend-select = ["I", "UP"]
|
|
99
|
+
|
|
100
|
+
[tool.ty.src]
|
|
101
|
+
include = ["mostlyai"]
|
|
102
|
+
|
|
103
|
+
[tool.ty.analysis]
|
|
104
|
+
# optional extra `mcp` is not installed in CI
|
|
105
|
+
allowed-unresolved-imports = ["fastmcp"]
|
|
File without changes
|
|
File without changes
|