Inférence IA (agent LangChain)

Fonctions réexportées par fabrictools pour l’inférence via un agent LangChain 1.x (create_agent, OpenRouter + recherche DuckDuckGo) et l’enrichissement de DataFrames Spark.

ai_response exécute un agent avec tool-calling : il peut interroger DuckDuckGo lorsque la question nécessite des informations récentes ou factuelles. Chaque appel peut déclencher plusieurs requêtes LLM et web (latence plus élevée qu’un chat simple).

exception fabrictools.AIError(message: str, *, status_code: int | None = None, error_code: str | None = None, response_body: str | None = None)

Bases: Exception

Raised when an OpenRouter chat completion request fails.

classmethod from_http_response(status_code: int, body: str) AIError[source]

Build an AIError from an HTTP status and response body.

fabrictools.ai_response(prompt: str, *, system_prompt: str | None = None, timeout_seconds: int = 60) str

Run a LangChain agent (OpenRouter + DuckDuckGo) and return the final answer.

The agent may search the web via DuckDuckGo when the prompt requires up-to-date or factual information. Each call can trigger multiple LLM and search requests.

Parameters:
  • prompt – User question or instruction.

  • system_prompt – Optional system instructions for the agent.

  • timeout_seconds – HTTP timeout in seconds (OpenRouter requests).

Returns:

Agent final answer text (stripped).

Return type:

str

Raises:

AIError – When the API key is missing, the agent fails, or the response is invalid.

Example

>>> ai_response("Quel est le cours du Bitcoin aujourd'hui ?")
>>> ai_response("Explique Delta Lake en 2 phrases.")
fabrictools.with_ai_column(df: pyspark.sql.DataFrame, output_col: str, prompt_template: str, *, input_cols: Sequence[str] | None = None, system_prompt: str | None = None, limit: int | None = None) pyspark.sql.DataFrame

Add output_col filled with an LLM response for each row.

The prompt is built from prompt_template using {column_name} placeholders resolved on df (physical, normalized, or snake_case labels).

Processing runs row-by-row on the Spark driver (one HTTP call per row). Use limit to cap processed rows; unprocessed rows receive null in output_col.

Parameters:
  • df – Input dataframe.

  • output_col – Name of the column to add.

  • prompt_template – Prompt with {placeholder} tokens for input columns.

  • input_cols – Explicit placeholder/column names; auto-detected from the template when omitted.

  • system_prompt – Optional system message for the model.

  • limit – Maximum number of rows to send to the model.

Returns:

Dataframe with output_col added.

Return type:

DataFrame

Raises:
  • ValueError – When placeholders or columns cannot be resolved.

  • AIError – When OpenRouter returns an error.

Example

>>> out = with_ai_column(
...     df,
...     "categorie_ia",
...     "Classe ce ticket : {sujet}{description}",
...     input_cols=["sujet", "description"],
...     limit=100,
... )
fabrictools.transform_ai_column(df: pyspark.sql.DataFrame, column: str, prompt_template: str, *, input_cols: Sequence[str] | None = None, system_prompt: str | None = None, limit: int | None = None) pyspark.sql.DataFrame

Replace column with an LLM response for each processed row.

Rows outside limit (when set) keep their original column value.

Parameters:
  • df – Input dataframe.

  • column – Target column to overwrite (resolved like other transform helpers).

  • prompt_template – Prompt with {placeholder} tokens for input columns.

  • input_cols – Explicit placeholder/column names; auto-detected from the template when omitted.

  • system_prompt – Optional system message for the model.

  • limit – Maximum number of rows to send to the model.

Returns:

Dataframe with column updated.

Return type:

DataFrame

Raises:
  • ValueError – When column or placeholders cannot be resolved.

  • AIError – When OpenRouter returns an error.

Example

>>> out = transform_ai_column(
...     df,
...     "resume",
...     "Résume en une phrase : {texte_long}",
...     system_prompt="Réponds uniquement avec le résumé.",
... )