# pysparky.functions.ai.llm

*module*

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/functions/ai/llm.py#L1-L1)

## pysparky.functions.ai.llm.build_text_generation_udf

*function*

```python
def build_text_generation_udf(model_bc: Broadcast, tokenizer_bc: Broadcast, system_prompt: str) -> UserDefinedFunction
```

Creates a Spark UDF for text generation using a Hugging Face model and tokenizer.

This function sets up a user-defined function (UDF) that can be used in Spark DataFrames
to perform text generation. It uses a broadcasted Hugging Face model and tokenizer to
ensure efficient distribution across Spark workers.

**Parameters**

- `model_bc` (`Broadcast`) — Broadcasted Hugging Face model.
- `tokenizer_bc` (`Broadcast`) — Broadcasted Hugging Face tokenizer.
- `system_prompt` (`str`) — Prompt to prepend to each input string before generation.

**Returns**

- `function` (`UserDefinedFunction`) — A Spark UDF that takes a string input and returns the generated text.

**Raises**

- `TypeError` — If `model_bc` or `tokenizer_bc` is not a Broadcast instance.

> **Example**
>
> ```python
> >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
> >>> model = AutoModelForSeq2SeqLM.from_pretrained("google/flan-t5-small")
> >>> tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-small")
> >>> t5_udf = build_text_generation_udf(
> ...     sc.broadcast(model), sc.broadcast(tokenizer), "sentiment of the text"
> ... )
> >>> results_df = input_df.withColumn("output_column", t5_udf("sentence"))
> ```

[View source](https://github.com/PySparky/pysparky-pyspark-helper/blob/327582f8b776fe7638082ce4b5be8153d3ce63d3/pysparky/functions/ai/llm.py#L15-L68)
