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

# Core Language Constructs

# Core Language Constructs

Based is built around a set of specialized constructs designed specifically for conversational AI workflows. These constructs provide a high-level abstraction that makes it easy to build complex interactions without getting lost in implementation details.

## The `say` Function

The `say` function generates a response from the AI to the user without expecting a reply. It's typically used to provide information, instructions, or acknowledgments.

**Syntax:**

```python theme={null}
say(message, exact=False, model=None)
```

**Parameters:**

* `message` (string): The content to be processed and presented to the user
* `exact` (boolean, optional): Controls how the message is processed
  * `True`: Outputs exactly what's provided in the message parameter, verbatim
  * `False` (default): Allows the AI to rephrase the message while maintaining its meaning
* `model` (string, optional): Specifies which AI model to use for processing the message (when exact=False)

**Return Value:**

* Returns the response text, which can be stored in a variable for later use or simply executed for its side effect

**Example:**

```python theme={null}
# Greet the user with an exact message
say("Welcome to BookBot! I'm here to help you find and reserve books.", exact=True)

# Generate a dynamic welcome based on intent
say("Generate a friendly welcome for a user looking for book recommendations")

# Store the response for later use
intro = say("Introduce yourself as a helpful assistant", model="anthropic/claude-3.7-sonnet")
```

## The `loop`, `talk`, and `until` Pattern

In Based, the `loop`, `talk`, and `until` constructs form an essential pattern that must be used together. This pattern creates interactive conversation flows that can repeat until specific conditions are met. The `talk` function is not meant to be used in isolation.

**Syntax:**

```python theme={null}
loop:
    response = talk(
        system_prompt,
        first_prompt=True,
        default_values={},
        info={}
    )
until "Description of the completion condition":
    # Validation code that determines if the condition is met
    # The loop continues until this code completes successfully
```

**Parameters for `talk`:**

* `system_prompt` (string): Instruction or prompt that guides the conversation
* `first_prompt` (boolean, optional): Controls conversation initiation
  * `True` (default): AI starts by sending the prompt message to the user
  * `False`: AI waits for the user to send a message first
* `default_values` (dict, optional): Example values to structure expected responses
* `info` (dict, optional): Additional context for the conversation

**The Loop-Until Pattern:**

* The `loop` keyword begins a repeatable conversation block
* The `talk` function within the loop handles the conversation exchange
* The `until` clause specifies a condition (in natural language) under which the loop should end
* The code block after `until` validates whether the condition has been met
  * If the condition is met (the code executes successfully), the loop exits
  * If the condition is not met, the loop repeats from the beginning

**Example:**

```python theme={null}
loop:
    book_preference = talk(
        "What genre of books do you enjoy reading?",
        True,
        {"genre": "mystery", "format": "paperback"}
    )
until "User provides a valid book genre and format":
    preference_data = book_preference.ask(
        question="Extract the user's book genre and preferred format.",
        example={"genre": "mystery", "format": "paperback"}
    )

    # Validate the genre and format
    if preference_data["genre"] not in ["mystery", "sci-fi", "romance", "non-fiction"]:
        print("Invalid genre provided. Re-prompting...")
        continue

    if preference_data["format"] not in ["paperback", "hardcover", "e-book", "audiobook"]:
        print("Invalid format provided. Re-prompting...")
        continue

    # If we reach here, both genre and format are valid
    print("Valid preferences received!")
```

## Data Processing Methods

Based provides powerful methods to transform and extract information from data objects. These methods can be applied to any data object, not just conversation responses.

### The `.ask` Method

The `.ask` method extracts structured data from any data object, transforming unstructured content into well-formed data that can be used programmatically. This method can be used with API responses, conversation results, or any other data.

**Syntax:**

```python theme={null}
data_object.ask(question, example=None, schema=None, model=None)
```

**Parameters:**

* `question` (string): Instruction for extracting specific information from the data
* `example` (dict, optional): Example object showing the expected output format
* `schema` (dict, optional): JSON schema defining the expected structure
* `model` (string, optional): AI model to use for extraction

**Return Value:**

* Returns structured data according to the example or schema provided

**Example:**

```python theme={null}
# Extract structured book preferences from a conversation response
preferences = response.ask(
    question="Extract the user's preferred book genre, format, and any specific authors they mentioned.",
    example={
        "genre": "mystery",
        "format": "audiobook",
        "authors": ["Agatha Christie", "Arthur Conan Doyle"]
    }
)

# Use .ask on an API response
response = requests.get(
    url='https://bookstore-api.example.com/books',
    headers={'Authorization': 'Bearer ' + auth_token},
    params={'genre': 'mystery'}
)
api_results = response.json().ask(
    question="Extract the book titles, authors, and prices from the API response.",
    example={"books": [{"title": "The Mystery", "author": "A. Writer", "price": "$12.99"}]}
)
```
