pipeline-smith 0.2.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.
File without changes
@@ -0,0 +1,52 @@
1
+ """
2
+ Wrapper around Palantir Foundry's Language Model Service.
3
+
4
+ Handles request building, retries with exponential backoff, and optional
5
+ token-based rate limiting — so callers just pass a model + prompt(s) and get
6
+ back results.
7
+
8
+ Public API:
9
+ call_llm(model, prompt, system_prompt=None, **kwargs) -> LLMResponse
10
+ call_llm_batch(model, prompts, system_prompt=None, max_workers=10, tokens_per_minute=None, **kwargs) -> list[LLMResponse]
11
+
12
+ Usage in a Foundry transform::
13
+
14
+ from dataclasses import asdict
15
+ from transforms.api import transform, Input, Output
16
+ from palantir_models.transforms import OpenAiGptChatLanguageModelInput
17
+ from palantir_models.models import OpenAiGptChatLanguageModel
18
+ from pipeline_smith.llm import call_llm_batch
19
+
20
+ COLUMN = "review_text"
21
+ SYSTEM_PROMPT = "Classify the sentiment as positive, negative, or neutral. Answer with a single word."
22
+
23
+ @transform(
24
+ reviews=Input("ri.foundry.main.dataset.xxx"),
25
+ model=OpenAiGptChatLanguageModelInput("ri.language-model-service..language-model.gpt-5-1"),
26
+ output=Output("ri.foundry.main.dataset.yyy"),
27
+ )
28
+ def compute_sentiment(ctx, reviews, model: OpenAiGptChatLanguageModel, output):
29
+ reviews_df = reviews.dataframe()
30
+
31
+ # Deduplicate to avoid redundant LLM calls
32
+ unique_values = reviews_df.select(COLUMN).distinct().rdd.flatMap(lambda row: row).collect()
33
+
34
+ # Batch call on unique values only
35
+ responses = call_llm_batch(
36
+ model, unique_values,
37
+ system_prompt=SYSTEM_PROMPT,
38
+ max_workers=8,
39
+ tokens_per_minute=80_000,
40
+ )
41
+
42
+ # Convert responses to a Spark DataFrame and join back
43
+ lookup = ctx.spark_session.createDataFrame([asdict(r) for r in responses])
44
+ lookup = lookup.withColumnRenamed("input_value", COLUMN)
45
+ result_df = reviews_df.join(lookup, on=COLUMN, how="left")
46
+ output.write_dataframe(result_df)
47
+ """
48
+
49
+ from pipeline_smith.llm.response import LLMResponse
50
+ from pipeline_smith.llm.service import call_llm, call_llm_batch
51
+
52
+ __all__ = ["call_llm", "call_llm_batch", "LLMResponse"]
@@ -0,0 +1,67 @@
1
+ import logging
2
+ import threading
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import List
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class Usage:
12
+ """Amount of the limit used at a time.monotonic() moment."""
13
+
14
+ at: float
15
+ amount: int
16
+
17
+
18
+ class RateLimiter:
19
+ """Thread-safe sliding-window rate limiter per minute, counting any unit (tokens, requests)."""
20
+
21
+ def __init__(self, limit_per_minute: int, unit: str = "tokens"):
22
+ self.limit_per_minute = limit_per_minute
23
+ self.unit = unit
24
+ self._lock = threading.Lock()
25
+ self._recent_usage: List[Usage] = []
26
+ self._full_until = 0.0
27
+
28
+ def _purge_expired(self):
29
+ cutoff = time.monotonic() - 60.0
30
+ self._recent_usage = [usage for usage in self._recent_usage if usage.at > cutoff]
31
+
32
+ def wait_and_consume(self, requested: int):
33
+ """Block until requested fits in what is left of the per-minute limit, then take it."""
34
+ while True:
35
+ with self._lock:
36
+ self._purge_expired()
37
+ used_last_minute = sum(usage.amount for usage in self._recent_usage)
38
+ remaining = self.limit_per_minute - used_last_minute
39
+ if time.monotonic() < self._full_until:
40
+ resume_at = self._full_until
41
+ elif requested <= remaining:
42
+ self._recent_usage.append(Usage(at=time.monotonic(), amount=requested))
43
+ return
44
+ else:
45
+ excess = requested - remaining
46
+ freed = 0
47
+ for usage in self._recent_usage:
48
+ freed += usage.amount
49
+ if freed >= excess:
50
+ break
51
+ resume_at = usage.at + 60.0
52
+ sleep_seconds = max(0.1, resume_at - time.monotonic())
53
+ logger.info(f"Rate limit: waiting {sleep_seconds:.1f}s ({used_last_minute} {self.unit} used in the last minute)")
54
+ time.sleep(sleep_seconds)
55
+
56
+ def fill(self):
57
+ """Let nothing through until the oldest usage of the last minute drops out, e.g. after the service
58
+ rejects a call for its rate limit. With no usage in the last minute, for a full minute."""
59
+ with self._lock:
60
+ self._purge_expired()
61
+ window_start = self._recent_usage[0].at if self._recent_usage else time.monotonic()
62
+ self._full_until = window_start + 60.0
63
+
64
+ def record(self, used: int):
65
+ """Record extra usage after the fact (e.g. output tokens once a call completes)."""
66
+ with self._lock:
67
+ self._recent_usage.append(Usage(at=time.monotonic(), amount=used))
@@ -0,0 +1,18 @@
1
+ import dataclasses
2
+ from typing import Optional, Union
3
+
4
+
5
+ @dataclasses.dataclass
6
+ class LLMResponse:
7
+ """Result of a single LLM call."""
8
+ input_value: Union[str, dict]
9
+ answer: Optional[str]
10
+ elapsed_seconds: float
11
+ input_tokens: int = 0
12
+ output_tokens: int = 0
13
+ error: Optional[str] = None
14
+
15
+
16
+ def estimate_tokens(text: str) -> int:
17
+ """Estimate token count from text using the ~4 chars/token heuristic."""
18
+ return max(1, len(text) // 4)
@@ -0,0 +1,233 @@
1
+ import json
2
+ import logging
3
+ import random
4
+ import time
5
+ from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from typing import List, Optional, Union
7
+
8
+ from pipeline_smith.llm.rate_limiter import RateLimiter
9
+ from pipeline_smith.llm.response import LLMResponse, estimate_tokens
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ MAX_ATTEMPTS = 3 # 1 initial try + 2 retries
14
+ RETRY_BACKOFF_SECONDS = [1, 2] # exponential backoff base: 1s, 2s
15
+ JITTER_MAX_SECONDS = 1.0 # random jitter added to each retry wait
16
+
17
+
18
+ def _supported_types() -> tuple:
19
+ """The Foundry model classes call_llm accepts.
20
+
21
+ Imported here rather than at module level so that importing pipeline_smith.llm
22
+ works in a repository without palantir_models installed: the LLM libraries are
23
+ only required once a call is actually made.
24
+ """
25
+ from palantir_models.models import OpenAiGptChatLanguageModel, GenericCompletionLanguageModel
26
+
27
+ return (OpenAiGptChatLanguageModel, GenericCompletionLanguageModel)
28
+
29
+
30
+ def _execute_call(model, prompt, system_prompt, **kwargs):
31
+ """Build the request, execute, and extract the answer based on model type."""
32
+ from palantir_models.models import OpenAiGptChatLanguageModel, GenericCompletionLanguageModel
33
+ from language_model_service_api.languagemodelservice_api_completion_v3 import (
34
+ GptChatCompletionRequest,
35
+ GenericCompletionRequest,
36
+ )
37
+ from language_model_service_api.languagemodelservice_api import ChatMessage, ChatMessageRole
38
+
39
+ if isinstance(model, OpenAiGptChatLanguageModel):
40
+ messages = []
41
+ if system_prompt is not None:
42
+ messages.append(ChatMessage(ChatMessageRole.SYSTEM, system_prompt))
43
+ messages.append(ChatMessage(ChatMessageRole.USER, prompt))
44
+ response = model.create_chat_completion(GptChatCompletionRequest(messages, **kwargs))
45
+ return response.choices[0].message.content
46
+
47
+ if isinstance(model, GenericCompletionLanguageModel):
48
+ full_prompt = f"{system_prompt}\n\n{prompt}" if system_prompt else prompt
49
+ response = model.create_completion(GenericCompletionRequest(full_prompt, **kwargs))
50
+ return response.completion
51
+
52
+ raise TypeError(
53
+ f"Unsupported model type: {type(model).__name__}. "
54
+ f"Supported: {', '.join(t.__name__ for t in _supported_types())}"
55
+ )
56
+
57
+
58
+ def call_llm(
59
+ model,
60
+ prompt: str,
61
+ system_prompt: Optional[str] = None,
62
+ request_rate_limiter: Optional[RateLimiter] = None,
63
+ **kwargs,
64
+ ) -> LLMResponse:
65
+ """
66
+ Call any supported LLM with a single prompt.
67
+
68
+ Auto-dispatches based on model type:
69
+ - OpenAiGptChatLanguageModel: sends system + user messages via create_chat_completion.
70
+ - GenericCompletionLanguageModel: sends a single prompt via create_completion.
71
+
72
+ Parameters
73
+ ----------
74
+ model
75
+ A Foundry model object (OpenAiGptChatLanguageModel or GenericCompletionLanguageModel).
76
+ prompt : str
77
+ The user prompt / main input to send to the model.
78
+ system_prompt : str, optional
79
+ System-level instruction. For chat models, sent as a SYSTEM message.
80
+ For generic models, prepended to the prompt.
81
+ request_rate_limiter : RateLimiter, optional
82
+ Requests-per-minute limiter shared across calls. Every attempt, retries included, takes a
83
+ slot from it, and a rate-limit rejection marks it full so no call starts until the minute passes.
84
+ **kwargs
85
+ Extra keyword arguments forwarded to the request constructor
86
+ (e.g. temperature=0, max_tokens=1000).
87
+
88
+ Returns
89
+ -------
90
+ LLMResponse
91
+ """
92
+ # Fail fast on unsupported model type
93
+ if not isinstance(model, _supported_types()):
94
+ raise TypeError(
95
+ f"Unsupported model type: {type(model).__name__}. "
96
+ f"Supported: {', '.join(t.__name__ for t in _supported_types())}"
97
+ )
98
+
99
+ input_tokens = estimate_tokens(prompt)
100
+ if system_prompt:
101
+ input_tokens += estimate_tokens(system_prompt)
102
+ last_error = None
103
+
104
+ for attempt in range(1, MAX_ATTEMPTS + 1):
105
+ if request_rate_limiter is not None:
106
+ request_rate_limiter.wait_and_consume(1)
107
+ start = time.monotonic()
108
+ try:
109
+ answer = _execute_call(model, prompt, system_prompt, **kwargs)
110
+ elapsed = time.monotonic() - start
111
+ output_tokens = estimate_tokens(answer)
112
+ logger.info(f"LLM call completed in {elapsed:.2f}s ({input_tokens}+{output_tokens} tokens)")
113
+ return LLMResponse(
114
+ input_value=prompt,
115
+ answer=answer,
116
+ elapsed_seconds=elapsed,
117
+ input_tokens=input_tokens,
118
+ output_tokens=output_tokens,
119
+ )
120
+ except (RuntimeError, OSError, ConnectionError) as exc:
121
+ elapsed = time.monotonic() - start
122
+ last_error = exc
123
+ rate_limited = "ratelimitsexceeded" in str(exc).lower()
124
+ if rate_limited and request_rate_limiter is not None:
125
+ request_rate_limiter.fill()
126
+ if attempt < MAX_ATTEMPTS:
127
+ if rate_limited and request_rate_limiter is not None:
128
+ logger.warning(
129
+ f"LLM call rate-limited (attempt {attempt}/{MAX_ATTEMPTS}): {exc}, "
130
+ f"retrying when the request window frees up"
131
+ )
132
+ continue
133
+ wait = RETRY_BACKOFF_SECONDS[attempt - 1] + random.uniform(0, JITTER_MAX_SECONDS)
134
+ logger.warning(f"LLM call failed (attempt {attempt}/{MAX_ATTEMPTS}): {exc}, retrying in {wait:.1f}s")
135
+ time.sleep(wait)
136
+
137
+ logger.error(f"LLM call failed after {MAX_ATTEMPTS} attempts (last attempt {elapsed:.2f}s): {last_error}")
138
+ return LLMResponse(
139
+ input_value=prompt,
140
+ answer=None,
141
+ elapsed_seconds=elapsed,
142
+ input_tokens=input_tokens,
143
+ error=str(last_error),
144
+ )
145
+
146
+
147
+ def call_llm_batch(
148
+ model,
149
+ prompts: List[Union[str, dict]],
150
+ system_prompt: Optional[str] = None,
151
+ max_workers: int = 10,
152
+ tokens_per_minute: Optional[int] = None,
153
+ requests_per_minute: Optional[int] = None,
154
+ **kwargs,
155
+ ) -> List[LLMResponse]:
156
+ """
157
+ Call any supported LLM in parallel for a list of prompts.
158
+
159
+ Parameters
160
+ ----------
161
+ model
162
+ A Foundry model object (OpenAiGptChatLanguageModel or GenericCompletionLanguageModel).
163
+ prompts
164
+ The prompts to process. A dict is sent as JSON, and its response carries the dict as input_value.
165
+ system_prompt
166
+ System-level instruction passed to each call.
167
+ max_workers
168
+ Number of parallel threads (default 10).
169
+ tokens_per_minute
170
+ Maximum tokens per minute across all threads. None (default) disables rate limiting.
171
+ requests_per_minute
172
+ Maximum calls started per minute across all threads, for a model whose quota counts
173
+ requests. Retries inside a call are not counted. None (default) disables it.
174
+ **kwargs
175
+ Extra keyword arguments forwarded to the request constructor
176
+ (e.g. temperature=0, max_tokens=1000).
177
+
178
+ Returns
179
+ -------
180
+ Results in the same order as the input prompts.
181
+ """
182
+ if not isinstance(model, _supported_types()):
183
+ raise TypeError(
184
+ f"Unsupported model type: {type(model).__name__}. "
185
+ f"Supported: {', '.join(t.__name__ for t in _supported_types())}"
186
+ )
187
+
188
+ logger.info(f"Starting batch LLM call: {len(prompts)} prompts, {max_workers} at a time")
189
+ rate_limiter = RateLimiter(tokens_per_minute) if tokens_per_minute is not None else None
190
+ # The sliding window counts any unit: one per call makes it a requests-per-minute limit.
191
+ request_rate_limiter = (
192
+ RateLimiter(requests_per_minute, unit="requests") if requests_per_minute is not None else None
193
+ )
194
+ system_tokens = estimate_tokens(system_prompt) if system_prompt else 0
195
+ results: List[Optional[LLMResponse]] = [None] * len(prompts)
196
+
197
+ def _rate_limited_call(prompt: Union[str, dict]) -> LLMResponse:
198
+ prompt_text = json.dumps(prompt) if isinstance(prompt, dict) else prompt
199
+ if rate_limiter is not None:
200
+ estimated_input_tokens = system_tokens + estimate_tokens(prompt_text)
201
+ rate_limiter.wait_and_consume(estimated_input_tokens)
202
+ response = call_llm(model, prompt_text, system_prompt, request_rate_limiter=request_rate_limiter, **kwargs)
203
+ if rate_limiter is not None and response.output_tokens > 0:
204
+ rate_limiter.record(response.output_tokens)
205
+ response.input_value = prompt
206
+ return response
207
+
208
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
209
+ future_to_position = {
210
+ executor.submit(_rate_limited_call, prompt): position
211
+ for position, prompt in enumerate(prompts)
212
+ }
213
+ completed = 0
214
+ errors = 0
215
+ for future in as_completed(future_to_position):
216
+ position = future_to_position[future]
217
+ results[position] = future.result()
218
+ completed += 1
219
+ if results[position].error is not None:
220
+ errors += 1
221
+ logger.info(
222
+ f"Batch progress: {completed}/{len(prompts)} done, "
223
+ f"{min(max_workers, len(prompts) - completed)} in flight, {errors} errors so far"
224
+ )
225
+
226
+ succeeded = sum(1 for r in results if r.error is None)
227
+ total_input_tokens = sum(r.input_tokens for r in results)
228
+ total_output_tokens = sum(r.output_tokens for r in results)
229
+ logger.info(
230
+ f"Batch complete: {succeeded}/{len(results)} succeeded, "
231
+ f"{total_input_tokens} input + {total_output_tokens} output tokens"
232
+ )
233
+ return results
@@ -0,0 +1,18 @@
1
+ """
2
+ Scope a Foundry schedule to one project with a connection build.
3
+
4
+ A connection build needs a build input upstream of every transform in the
5
+ project and a build target downstream of every one:
6
+
7
+ find_transform_instances(package) -> {"<module>_<index>": output alias}
8
+ every transform output in a package, to feed a schedule_build_target
9
+ transform that takes them all as inputs.
10
+ add_schedule_build_input(pipeline, alias) -> None
11
+ gives every transform on a discovered Pipeline a hand-made dataset as
12
+ an extra Input its compute function never sees; usage in its docstring.
13
+ """
14
+
15
+ from pipeline_smith.schedule.build_input import add_schedule_build_input
16
+ from pipeline_smith.schedule.find_transforms import find_transform_instances
17
+
18
+ __all__ = ["add_schedule_build_input", "find_transform_instances"]
@@ -0,0 +1,61 @@
1
+ import functools
2
+
3
+ from transforms.api import Pipeline, Input
4
+ from transforms.api._incremental import _IncrementalCompute
5
+
6
+
7
+ def add_schedule_build_input(pipeline: Pipeline, alias: str) -> None:
8
+ """Give every transform on *pipeline* the schedule build input as an Input its compute function never sees.
9
+
10
+ *alias* is what ``transforms.api.Input`` takes: an absolute Compass path or a dataset rid. With
11
+ that dataset upstream of every transform, a schedule from it to the project's build target is a
12
+ connection build over the project and nothing else. Incremental transforms get it as a snapshot
13
+ input, so a new transaction on it never forces a full recompute.
14
+
15
+ Usage, in the project's ``pipeline.py`` after discovery::
16
+
17
+ from transforms.api import Pipeline
18
+ from pipeline_smith.schedule import add_schedule_build_input
19
+
20
+ from myproject import datasets
21
+
22
+ my_pipeline = Pipeline()
23
+ my_pipeline.discover_transforms(datasets)
24
+ add_schedule_build_input(my_pipeline, alias="/Project/datasets/schedule_build_input")
25
+
26
+ The dataset is created by hand and needs one committed transaction.
27
+ """
28
+ # Lightweight transforms.
29
+ for container_transform in pipeline.container_transforms_configurations:
30
+ container_transform._transform.inputs["schedule_build_input"] = Input(alias)
31
+ container_transform._transform.parameters["schedule_build_input"] = (
32
+ container_transform._transform.inputs["schedule_build_input"]
33
+ )
34
+ # Keep incremental transforms incremental: the new input is a snapshot input.
35
+ if container_transform._incremental.is_incremental:
36
+ object.__setattr__(
37
+ container_transform._incremental,
38
+ "snapshot_inputs",
39
+ [*(container_transform._incremental.snapshot_inputs or []), "schedule_build_input"],
40
+ )
41
+
42
+ # Spark transforms.
43
+ for transform in pipeline.transforms:
44
+ transform.inputs["schedule_build_input"] = Input(alias)
45
+ transform.parameters["schedule_build_input"] = transform.inputs["schedule_build_input"]
46
+ # Keep incremental transforms incremental: the new input is a snapshot input.
47
+ if isinstance(transform.compute, _IncrementalCompute):
48
+ transform.compute._snapshot_inputs.append("schedule_build_input")
49
+ # Checks: Transform.validate requires every input to be a parameter of the compute
50
+ # function, so the name is appended to the recorded argspec.
51
+ transform._argspec = transform._argspec._replace(args=[*transform._argspec.args, "schedule_build_input"])
52
+ # Runtime: Foundry calls the compute function with every input as a keyword argument, so a
53
+ # wrapper drops this one first.
54
+ compute_func = transform._compute_func
55
+
56
+ @functools.wraps(compute_func)
57
+ def compute_without_schedule_build_input(*args, compute_func=compute_func, **kwargs): # bound per iteration
58
+ kwargs.pop("schedule_build_input")
59
+ return compute_func(*args, **kwargs)
60
+
61
+ transform._compute_func = compute_without_schedule_build_input
@@ -0,0 +1,63 @@
1
+ """
2
+ Collect Transform output aliases from a package — useful for populating
3
+ ``schedule_build_target`` when registering Foundry schedules via API.
4
+
5
+ See: https://www.linkedin.com/posts/pietro-castoldi_palantir-foundry-dataengineering-activity-7424402566383484928-uaPj
6
+ """
7
+
8
+ import importlib
9
+ import inspect
10
+ import logging
11
+ import pkgutil
12
+ from types import ModuleType
13
+ from typing import Dict, List
14
+
15
+ from transforms.api._lightweight._transform import ContainerTransform
16
+ from transforms.api._transform import Transform
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def find_transform_instances(root_module: ModuleType) -> Dict[str, str]:
22
+ """Walk *root_module* and sub-modules, returning ``{"<module>:<index>": alias}`` for every transform output.
23
+
24
+ Transforms are collected from module attributes and from module-level
25
+ lists/tuples of transforms (the Foundry transform-generation pattern).
26
+ """
27
+ if not isinstance(root_module, ModuleType):
28
+ raise TypeError(f"Expected a module/package, got {type(root_module).__name__}")
29
+
30
+ module_names = [root_module.__name__]
31
+ if hasattr(root_module, "__path__"):
32
+ module_names.extend(
33
+ module.name for module in pkgutil.walk_packages(root_module.__path__, prefix=f"{root_module.__name__}.")
34
+ )
35
+
36
+ result = {}
37
+ for full_name in module_names:
38
+ try:
39
+ module = importlib.import_module(full_name)
40
+ except Exception as exc:
41
+ logger.warning("Could not import %s – skipped (%s)", full_name, exc)
42
+ continue
43
+
44
+ aliases = []
45
+ seen_transform_ids = set()
46
+ for _, obj in inspect.getmembers(module):
47
+ members = obj if isinstance(obj, (list, tuple)) else [obj]
48
+ for member in members:
49
+ if getattr(member, "__module__", None) != full_name:
50
+ continue
51
+ if id(member) in seen_transform_ids:
52
+ continue
53
+ if isinstance(member, ContainerTransform):
54
+ seen_transform_ids.add(id(member))
55
+ aliases.extend(member._transform._output_aliases)
56
+ elif isinstance(member, Transform):
57
+ seen_transform_ids.add(id(member))
58
+ aliases.extend(member._output_aliases)
59
+
60
+ for idx, alias in enumerate(aliases):
61
+ result[f"{full_name}_{idx}"] = alias
62
+
63
+ return result
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ from typing import TYPE_CHECKING, List, Optional
5
+
6
+ from pyspark.sql import DataFrame, Window, functions as F
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from transforms.api._transform import TransformOutput
11
+
12
+
13
+ def write_spark_dataframe_repartitioned(output_to: TransformOutput, df: DataFrame, rows_per_file: int, partition_columns: Optional[List[str]] = None, **kwargs):
14
+ """Write a Spark *dataframe* to *output_to*, repartitioning to target ~*rows_per_file* rows per output file.
15
+
16
+ Controls the number and size of output files — avoids the small-file problem (too many tiny files)
17
+ and oversized partitions (too few large files).
18
+
19
+ Example — basic usage with a known rows_per_file:
20
+
21
+ write_spark_dataframe_repartitioned(output_to=my_output, df=df, rows_per_file=500_000)
22
+
23
+ Example — dynamically calculate rows_per_file from previous build metadata:
24
+
25
+ TARGET_FILE_SIZE = 150 * 1024 * 1024 # 150 MB
26
+
27
+ previous_files = output_to.filesystem().ls(mode="previous")
28
+ total_size = sum(f.size for f in previous_files)
29
+
30
+ previous_df = output_to.dataframe(mode="previous", schema=output_to.dataframe(mode="current").schema)
31
+ combined_df = previous_df.unionByName(df)
32
+ combined_rows = combined_df.count()
33
+
34
+ rows_per_file = max(1, int(combined_rows * TARGET_FILE_SIZE / total_size))
35
+ output_to.set_mode("replace")
36
+ write_spark_dataframe_repartitioned(output_to=output_to, df=combined_df, rows_per_file=rows_per_file)
37
+ """
38
+ if not hasattr(output_to, "write_dataframe"):
39
+ raise TypeError(f"Expected a TransformOutput with write_dataframe method, got {type(output_to).__name__}")
40
+
41
+ if not isinstance(df, DataFrame):
42
+ raise TypeError(f"Expected a PySpark DataFrame, got {type(df).__name__}")
43
+
44
+ if rows_per_file < 1:
45
+ raise ValueError(f"rows_per_file must be >= 1, got {rows_per_file}")
46
+
47
+ total_rows = df.count()
48
+ num_files = max(1, math.ceil(total_rows / rows_per_file))
49
+
50
+ df.sparkSession.conf.set("spark.sql.files.maxRecordsPerFile", rows_per_file)
51
+
52
+ salt_column = "_salt"
53
+ if partition_columns:
54
+ partition_window = Window.partitionBy(partition_columns)
55
+ partition_count = F.count("*").over(partition_window)
56
+ files_in_partition = F.greatest(F.lit(1), F.floor(partition_count / rows_per_file))
57
+ salted = df.withColumn(salt_column, (F.rand() * files_in_partition).cast("int"))
58
+ else:
59
+ salted = df.withColumn(salt_column, F.monotonically_increasing_id() % num_files)
60
+ partition_columns = []
61
+
62
+ repartition_columns = [F.col(column) for column in partition_columns] + [F.col(salt_column)]
63
+ repartitioned = salted.repartition(num_files, *repartition_columns).drop(salt_column)
64
+
65
+ output_to.write_dataframe(repartitioned, partition_cols=partition_columns, **kwargs)
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: pipeline-smith
3
+ Version: 0.2.0
4
+ Summary: A portable Python toolkit for data pipeline development on Palantir Foundry
5
+ Author: Library
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Requires-Python: >=3.11
11
+ Provides-Extra: pyspark
12
+ Requires-Dist: pyspark>=3.4; extra == 'pyspark'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # pipeline-smith
16
+
17
+ A portable Python toolkit for data pipeline development on Palantir Foundry.
18
+
19
+ In Foundry, open the **Libraries** panel and add `pipeline-smith` from the pip libraries, then `import pipeline_smith`.
20
+
21
+ ---
22
+
23
+ ## 1. LLM calls
24
+
25
+ `pipeline_smith.llm` wraps Foundry-hosted LLM providers behind a uniform interface so you can swap models without changing calling code.
26
+
27
+ ### Single call
28
+
29
+ ```python
30
+ from pipeline_smith.llm import call_llm
31
+
32
+ response = call_llm(model=model, prompt="Great product!", system_prompt="Classify sentiment.")
33
+ print(response.answer) # model's response text
34
+ print(response.elapsed_seconds) # time taken
35
+ print(response.error) # None on success, error message on failure
36
+ ```
37
+
38
+ ### Batch call (parallel)
39
+
40
+ ```python
41
+ from pipeline_smith.llm import call_llm_batch
42
+
43
+ responses = call_llm_batch(
44
+ model=model,
45
+ prompts=["Great product!", "Terrible service.", "It was okay."],
46
+ system_prompt="Classify sentiment.",
47
+ max_workers=8,
48
+ )
49
+ for r in responses:
50
+ print(r.input_value, "->", r.answer)
51
+ ```
52
+
53
+ ### Usage in a Foundry transform
54
+
55
+ ```python
56
+ from transforms.api import transform, Input, Output
57
+ from palantir_models.transforms import OpenAiGptChatLanguageModelInput
58
+ from palantir_models.models import OpenAiGptChatLanguageModel
59
+ from pipeline_smith.llm import call_llm_batch
60
+
61
+ @transform(
62
+ data=Input("..."),
63
+ model=OpenAiGptChatLanguageModelInput("ri.language-model-service..language-model.gpt-5-1"),
64
+ output=Output("..."),
65
+ )
66
+ def compute(ctx, data, model: OpenAiGptChatLanguageModel, output):
67
+ df = data.pandas()
68
+ responses = call_llm_batch(
69
+ model=model,
70
+ prompts=df["text"].tolist(),
71
+ system_prompt="Classify sentiment.",
72
+ max_workers=8,
73
+ )
74
+ df["sentiment"] = [r.answer for r in responses]
75
+ output.write_dataframe(ctx.spark_session.createDataFrame(df))
76
+ ```
77
+
78
+ ### Adding a new model provider
79
+
80
+ In `service.py`, add the model class to `_supported_types` and an `isinstance` branch in `_execute_call`.
81
+
82
+ ---
83
+
84
+ ## 2. Schedule build input code setup
85
+
86
+ A schedule scoped as a connection build needs a build input upstream of every transform in the project and a build target downstream of every one. Both ends come from the project's `pipeline.py`:
87
+
88
+ - `pipeline_smith.schedule.find_transform_instances(package)` returns every transform output in a package, to feed a `schedule_build_target` transform that takes them all as inputs.
89
+ - `pipeline_smith.schedule.add_schedule_build_input(pipeline, alias)` gives every discovered transform a hand-made dataset as an extra `Input` its compute function never sees, so that one dataset sits upstream of the whole project. Usage and the schedule setup are in its docstring.
90
+
91
+ ---
92
+
93
+ ## 3. Integration test setup
94
+
95
+ > **TBD** — placeholder section.
@@ -0,0 +1,13 @@
1
+ pipeline_smith/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ pipeline_smith/write_dataset.py,sha256=W1GYXFFUk64w3vfY_3NPdId2MR6dregaR1D-UXYGQR4,2863
3
+ pipeline_smith/llm/__init__.py,sha256=bjjUReeNERMMRX0gvP1t6svndLLDjhpJLsotkLWYV6o,2128
4
+ pipeline_smith/llm/rate_limiter.py,sha256=VBHQZx0mXHnZwMBu-mx2JdCfyubz2rcyNFd7vv0mUvQ,2693
5
+ pipeline_smith/llm/response.py,sha256=wwLwqss3-vt7QVvV4Vt84BOqwXHywUef25Y4ltimyHo,461
6
+ pipeline_smith/llm/service.py,sha256=fJl3_NaVL0SG3OYXMayTl6tZdEoh3nN55zjRH93qx30,9698
7
+ pipeline_smith/schedule/__init__.py,sha256=wEBY4ffzNKkepKyB6GyuPpVVvP5KGqckCrGWUqM-Zao,834
8
+ pipeline_smith/schedule/build_input.py,sha256=llGlrRxFKYxyk259QvyRsVps3QaNVeCbJwy_ktM7XSA,3122
9
+ pipeline_smith/schedule/find_transforms.py,sha256=8adRkYMk7H9vEhGXKyAf6jhkIO6pda-XyElep6PAzqg,2389
10
+ pipeline_smith-0.2.0.dist-info/METADATA,sha256=SvFhfKLOaLmyR2IBWKnS1MKd7Vmu_v9mP2Wv-Kl1FUA,3221
11
+ pipeline_smith-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
12
+ pipeline_smith-0.2.0.dist-info/licenses/LICENSE,sha256=8PnWFL9aaTsmTMHF2I5x_QucINuH5Q-TLWJFTF3qWZc,1083
13
+ pipeline_smith-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pietro Alessandro Castoldi
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.