> ## Documentation Index
> Fetch the complete documentation index at: https://docs.liquid.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced Features

> GenerationOptions, JSONSchemaGenerator, function-calling type references — same surface everywhere.

This page consolidates the lower-level reference symbols used by [Constrained Generation](./constrained-generation) and [Function Calling](./function-calling). Most apps don't touch these directly — the high-level pages cover the usual flows. Reach here when you need to inspect schemas, build options programmatically, or wire a custom parser.

## `GenerationOptions`

Per-request controls. Leave any field as `null` / `nil` to fall back to the manifest defaults.

<Tabs>
  <Tab title="Swift (iOS / macOS)">
    `GenerationOptions` is a Kotlin `data class` bridged into Swift. Kotlin parameter defaults don't survive the ObjC bridge, so the canonical Swift idiom is the parameterless init plus chained `.with(...)` builders:

    ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
    public class GenerationOptions {
      public var temperature: Float?
      public var topP: Float?
      public var minP: Float?
      public var repetitionPenalty: Float?
      public var topK: Int32?
      public var rngSeed: Int64?
      public var jsonSchemaConstraint: String?
      public var functionCallParser: LeapFunctionCallParser?
      public var injectSchemaIntoPrompt: Bool        // default true
      public var maxTokens: Int32?
      public var inlineThinkingTags: Bool            // default false
      public var enableThinking: Bool                // default false
      public var extras: String?

      public convenience init()
    }
    ```

    Builder-style chaining (v0.10.0+):

    ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
    let opts = GenerationOptions()
        .with(temperature: 0.3)
        .with(minP: 0.15)
        .with(repetitionPenalty: 1.05)
        .with(jsonSchema: CityFact.jsonSchema())   // or any other schema string
    ```

    For the legacy compat-class path (`Leap.load(...)` flows), `GenerationOptionsCompat` additionally exposes `setResponseFormat(jsonSchema: String)`.
  </Tab>

  <Tab title="Kotlin (all platforms)">
    ```kotlin theme={"theme":{"light":"github-light","dark":"github-dark"}}
    data class GenerationOptions(
        var temperature: Float? = null,
        var topP: Float? = null,
        var minP: Float? = null,
        var repetitionPenalty: Float? = null,
        var topK: Int? = null,
        var rngSeed: Long? = null,
        var jsonSchemaConstraint: String? = null,
        var functionCallParser: LeapFunctionCallParser? = LFMFunctionCallParser(),
        var injectSchemaIntoPrompt: Boolean = true,
        var maxTokens: Int? = null,
        var inlineThinkingTags: Boolean = false,
        var enableThinking: Boolean = false,
        var extras: String? = null,
    ) {
        inline fun <reified T : Any> setResponseFormatType()

        companion object {
            fun build(buildAction: GenerationOptions.() -> Unit): GenerationOptions
        }
    }
    ```
  </Tab>
</Tabs>

* **Sampling fields** — `temperature`, `topP`, `minP`, `topK`, and `repetitionPenalty`. Use the model bundle's recommended values; arbitrary defaults from generic tutorials usually underperform.
* **`rngSeed`** — deterministic sampling seed for tests and reproducible runs.
* **`maxTokens`** — maximum completion tokens to generate. Prompt tokens do not count toward this cap.
* **`jsonSchemaConstraint`** — JSON Schema string for constrained generation. Use the higher-level helpers — Swift `options.with(jsonSchema: T.jsonSchema())` / Kotlin `setResponseFormatType<T>()` — instead of writing the schema by hand.
* **`injectSchemaIntoPrompt`** — when `true` (default), the schema is also appended to the system message for semantic guidance. Set `false` to use only the structural constraint.
* **`functionCallParser`** — `LFMFunctionCallParser` (default), `HermesFunctionCallParser()`, or `null`/`nil` to disable parsing and surface raw tool-call text in `Chunk`s.
* **`enableThinking` / `inlineThinkingTags`** — reasoning-mode controls for models that emit `<think>` content.
* **`extras`** — backend-specific JSON payload.

## Constrained generation utilities

<Tabs>
  <Tab title="Swift (iOS / macOS)">
    ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
    // Compile-time schema synthesis lives in the @Generatable macro.
    // For ad-hoc inspection (ships in the LeapSDKMacros SPM product):
    import LeapSDKMacros

    let schemaString = JSONSchemaGenerator.getJSONSchema(for: CityFact.self)
    ```

    `JSONSchemaGenerator.getJSONSchema(for:)` is non-throwing — it forwards to the `jsonSchema()` method that the `@Generatable` macro adds to the type, so the schema is produced at compile time. Useful when embedding the schema in the prompt itself, or when you want to debug the schema the model is being constrained against.

    See [Constrained Generation](./constrained-generation) for the full `@Generatable` / `@Guide` macro reference.
  </Tab>

  <Tab title="Kotlin (all platforms)">
    ### `JSONSchemaGenerator`

    ```kotlin theme={"theme":{"light":"github-light","dark":"github-dark"}}
    package ai.liquid.leap.structuredoutput

    object JSONSchemaGenerator {
      @Throws(LeapGeneratableSchematizationException::class)
      fun <T : Any> getJSONSchema(serializer: KSerializer<T>, indentSpaces: Int? = null): String

      @Throws(LeapGeneratableSchematizationException::class)
      inline fun <reified T : Any> getJSONSchema(indentSpaces: Int? = null): String
    }
    ```

    * `serializer` — the `KSerializer<T>` for a data class annotated with `@Generatable` and `@Serializable`. The reified-`T` overload calls `serializer<T>()` for you.
    * `indentSpaces` — non-null formats the output with the given indent (pretty-print).

    Throws `LeapGeneratableSchematizationException` if the class can't be translated.

    ### `GeneratableFactory`

    ```kotlin theme={"theme":{"light":"github-light","dark":"github-dark"}}
    import kotlinx.serialization.json.JsonObject

    object GeneratableFactory {
      @Throws(LeapGeneratableDeserializationException::class)
      fun <T : Any> createFromJsonObject(jsonObject: JsonObject, serializer: KSerializer<T>): T

      @Throws(LeapGeneratableDeserializationException::class)
      inline fun <reified T : Any> createFromJsonObject(jsonObject: JsonObject): T
    }
    ```

    Note the camelCase `Json` in the method name and the `kotlinx.serialization.json.JsonObject` argument (not `org.json.JSONObject`). The reified-`T` overload is a convenience when the target type can be inferred from context.

    ### Annotations

    ```kotlin theme={"theme":{"light":"github-light","dark":"github-dark"}}
    package ai.liquid.leap.structuredoutput

    @Target(AnnotationTarget.CLASS)
    annotation class Generatable(val description: String)

    @Target(AnnotationTarget.PROPERTY)
    annotation class Guide(val description: String)
    ```
  </Tab>
</Tabs>

## Function-calling type reference

The full surface is documented in [Function Calling](./function-calling); the type signatures here are the at-a-glance reference.

<Tabs>
  <Tab title="Swift (iOS / macOS)">
    ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
    public struct LeapFunction {
      public let name: String
      public let description: String
      public let parameters: [LeapFunctionParameter]
    }

    public struct LeapFunctionParameter {
      public let name: String
      public let type: LeapFunctionParameterType
      public let description: String
      public let optional: Bool
    }

    public indirect enum LeapFunctionParameterType: Codable, Equatable {
      case string(StringType)
      case number(NumberType)
      case integer(IntegerType)
      case boolean(BooleanType)
      case array(ArrayType)
      case object(ObjectType)
      case null(NullType)
    }

    public struct LeapFunctionCall {
      public let name: String
      public let arguments: [String: Any?]
    }
    ```

    Type wrappers (`StringType`, `NumberType`, etc.) carry per-type metadata like `enumValues` for restricting valid inputs and `description` for prompt-time hints (used when the type is nested inside an array or object).
  </Tab>

  <Tab title="Kotlin (all platforms)">
    ```kotlin theme={"theme":{"light":"github-light","dark":"github-dark"}}
    data class LeapFunction(
        val name: String,
        val description: String,
        val parameters: List<LeapFunctionParameter>,
    )

    data class LeapFunctionParameter(
        val name: String,
        val type: LeapFunctionParameterType,
        val description: String,
        val optional: Boolean = false,
    )

    sealed class LeapFunctionParameterType(typeDescription: kotlin.String? = null) {
      var description: kotlin.String? = typeDescription
        private set

      // Nested class names carry a `Leap` prefix so they don't shadow `kotlin.String`,
      // `kotlin.Number`, etc. at use sites.
      class LeapStr(val enumValues: List<kotlin.String>? = null, description: kotlin.String? = null) : LeapFunctionParameterType(description)
      class LeapNum(val enumValues: List<kotlin.Number>? = null, description: kotlin.String? = null) : LeapFunctionParameterType(description)
      class LeapInt(val enumValues: List<Int>? = null, description: kotlin.String? = null) : LeapFunctionParameterType(description)
      class LeapBool(description: kotlin.String? = null) : LeapFunctionParameterType(description)
      class LeapNull : LeapFunctionParameterType()
      class LeapArr(val itemType: LeapFunctionParameterType, description: kotlin.String? = null) : LeapFunctionParameterType(description)
      class LeapObj(
        val properties: Map<kotlin.String, LeapFunctionParameterType>,
        val required: List<kotlin.String> = listOf(),
        description: kotlin.String? = null,
      ) : LeapFunctionParameterType(description)
    }

    data class LeapFunctionCall(
        val name: String,
        val arguments: Map<String, Any?>,
    )
    ```
  </Tab>
</Tabs>

### Parsers

Two parser implementations ship with the SDK on every platform:

* **`LFMFunctionCallParser`** — default. Handles Liquid Foundation Model (LFM2) Pythonic-style control tokens (`<|tool_call_start|>` / `<|tool_call_end|>`).
* **`HermesFunctionCallParser`** — Qwen3 and other models using the [Hermes function-calling format](https://github.com/NousResearch/Hermes-Function-Calling).

Subclass `LeapFunctionCallParser` (Kotlin `abstract class`, bridged to Swift as a class with the same name) to add support for a new format.

## Prompt token budgeting

`getPromptTokensSize(messages:, addBosToken:)` is declared directly on `ModelRunner` — no cast required. Useful when you need to estimate context usage before sending a long request.

<Tabs>
  <Tab title="Swift (iOS / macOS)">
    ```swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
    let count = try await runner.getPromptTokensSize(messages: history, addBosToken: true)
    print("Prompt would consume \(count) tokens")
    ```
  </Tab>

  <Tab title="Kotlin (all platforms)">
    ```kotlin theme={"theme":{"light":"github-light","dark":"github-dark"}}
    val count = runner.getPromptTokensSize(messages = history, addBosToken = true)
    println("Prompt would consume $count tokens")
    ```

    `getPromptTokensSize` is `suspend` — call it from a coroutine.
  </Tab>
</Tabs>
