---
updatedAt: 2025-11-11T21:50:22.000Z
agentTools:
  projectIndex: https://ai-studio-docs.quiq.com/llms.txt
---

# Python Function Runtime

# Python Function Runtime

The Python Function Runtime allows you to author functions (such as prompt builders and completion handlers) using a limited version of the Python programming language. The runtime is only intended for writing pure functions and is not a general software runtime. Think of it as a templating engine on steroids. Rather than worrying about network requests, concurrency and other software engineering concerns, you can just focus on minimal scripting to achieve the desired translations.

* Compatible with Python 3.12 syntax
* Each assistant gets one python module in which to author functions referenced directly by the Flow or lower-level helper functions
* To aide in debugging, `print` output is visible in the Debug Workbench -> Inspector -> Console  area
* The `import` keyword is not allowed.
* The only module you have access to is the pre-imported `quiq` module that contains various helper functions documented below
* There's no way to make network requests from within your functions. However, search results and webhook results accumulate on the `context` argument that is passed into your assistant functions

Reference Materials

* [Example Functions](https://ai-studio-docs.quiq.com/docs/ai-studio-function-examples)

# quiq.base64

## encode

```python
def encode(bites, url=False)
```

Encode a bytes-like object using python's base64 standard library

**Arguments**:

* `bites` *bytes* - a bytes-like object to base64 encode
* `url` *bool* - whether or not to encode to a base64 URL scheme

**Returns**:

Base64 encoded bytes

## decode

```python
def decode(bites, url=False)
```

Decode a bytes-like object using python's base64 standard library

**Arguments**:

* `bites` *bytes* - a bytes-like object to base64 decode
* `url` *bool* - whether or not to decode from a base64 URL scheme

**Returns**:

Bytes decoded from base64

## encode\_to\_string

```python
def encode_to_string(string, url=False, charset="utf-8")
```

Base64 encode a string using python's base64 standard library

**Arguments**:

* `string` *str|bytes* - a str (or bytes) to base64 encode
* `url` - (bool): whether or not this is to be encoded to a base64 URL scheme
* `charset` *str* - defaults to utf-8

**Returns**:

The base64 encoded string generated from the input argument

## decode\_to\_string

```python
def decode_to_string(string, url=False, charset="utf-8")
```

Base64 decode a string using python's base64 standard library

**Arguments**:

* `string` *str|bytes* - a str (or bytes) to base64 decode
* `url` *bool* - whether or not this is to be decoded from a base64 URL scheme
* `charset` *str* - defaults to utf-8

**Returns**:

The string decoded from the base64 input.

# quiq.copy

## safe\_deepcopy

```python
def safe_deepcopy(o)
```

Make a deep copy of an object

# quiq.ctx

## import\_magic

```python
def import_magic()
```

Loads all of the functions defined in this module into the global namespace so that you can reference them like `get_context()` instead of `quiq.ctx.get_context()`

## get\_context

```python
def get_context()
```

Fetch the context object if you don't have a reference to it

## config

```python
def config(name)
```

Get the value of a config defined on your AI project

## get\_field

```python
def get_field(field, d=None, apply_default=True)
```

Check/fetch the state of a field in your AI project

Get the state of a field in your AI project with an optional default. You can provide an explicit default to be used, or you\
will get the default default based on the field type.

Default default values:

* `string`: `''`, unless it's an enum field in which case `None`
* `buffer`: `{}`
* `boolean`: `false`
* `integer`: `0`
* `number`: `0.0`

**Arguments**:

* `field` *str* - The name of the field to fetch, e.g. 'answer'
* `d` - An explicit default value you can specify if you don't want the default default
* `apply_default` *boolean* - Whether or not to apply a default value. If no default is applied and a field is not set, function will return `None`

**Returns**:

The current field value or default if not set

## set\_field

```python
def set_field(field, value, strict=True)
```

Generate an action to set the state of a field defined on your AI project

Generate an action to set the state of a field. The value you supply will be validated according to the data dictionary. If the value\
you supply is invalid, an Exception will be thrown.

**Arguments**:

* `field` *str* - The field to set
* `value` - The value to put in the field
* `strict` *boolean* - If False validation will attempt to coerce your value to make it legal, e.g. trimming a string down to its max length. Default: True

**Returns**:

An action to set the field that you should return in your actions array

## unset\_field

```python
def unset_field(field)
```

Generate an action to unset the state of a field defined on your AI project.

## get\_search\_results

```python
def get_search_results(resource_id, max_distance=None, max_records=None)
```

Easily find search results for a given search resource.

Finds search results by search resource id with the ability to apply a distance filter.

**Arguments**:

* `resource_id` *str* - The id of the search index
* `max_distance` *float* - Optional max distance between the search result and the search string
* `max_records` *int* - Optional maximum number of records to return

**Returns**:

A list of dataset records, the schema of which varies based on the dataset.

## format\_search\_results

```python
def format_search_results(resource_id,
                          format_str,
                          records=None,
                          separator="\n\n",
                          max_distance=None,
                          max_records=None)
```

Easily format search result into a string (typically for inclusion in prompts)

Finds and formats search results by search resource id with the ability to apply a distance filter.

Example invocation assuming dataset records ahve the properties `title` and `body`:

`quiq.ctx.format_search_results('my-search-resource', "{title} - {body}")`

**Arguments**:

* `resource_id` *str* - The id of the search resource
* `format_str` *str* - A python f-string (format string) that will be used to format the search records
* `records` - (list): Overrides the list of records to format. By default will be populated for you using `get_search_results`
* `separator` - (str): Separator to be used between records in the final formatted string.
* `max_distance` *float* - Optional max distance between the search result and the search string
* `max_records` *int* - Optional maximum number of records to return

**Returns**:

A string representation of the matching search results

# quiq.dt

## timestamp\_to\_iso

```python
def timestamp_to_iso(timestamp, tz=None)
```

Convert timestamp to an ISO 8601 string

Converts timestamps into ISO 8601 strings. Will handle either second or millisecond timestamps. By default the ISO\
strings will be in UTC but you can override that.

**Arguments**:

* `timestamp` - the timestamp in seconds or milliseconds. Can be a float or int
* `tz` - Optional tz, which must be a legal key into the IANA zone\_info DB. Defaults to UTC.

**Returns**:

An ISO 8601 string

## iso\_to\_timestamp

```python
def iso_to_timestamp(iso_string)
```

Convert an ISO 8601 string to a timestamp

**Arguments**:

* `iso_string` *str* - A legal ISO 8601 datetime string

**Returns**:

A unix timestamp (in seconds) as a float

## format\_timestamp

```python
def format_timestamp(timestamp, format_str, tz=None)
```

Format a timestamp according to a format string.

See the [python docs](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) for details on supported format strings

**Arguments**:

* `timestamp` - the timestamp in seconds or milliseconds. Can be a float or int
* `format_str` - the formatting string to apply to the timestamp
* `tz` - Optional tz, which must be a legal key into the IANA zone\_info DB. Defaults to UTC.

**Returns**:

The formatted string

## string\_to\_timestamp

```python
def string_to_timestamp(string, format_str)
```

Use a format string to convert a string date/datetime to a timestamp.

See the [python docs](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior) for details on supported format strings

**Arguments**:

* `string` - the string containing a date or datetime in a well structured format
* `format_str` - the formatting string that describes how the data is encoded in `string`

**Returns**:

The timestamp

# quiq.json

## loads

```python
def loads(s)
```

Deserialize a JSON string into an object

## loads\_sloppy

```python
def loads_sloppy(string)
```

Variant of loads that tries its best to work around issues with LLM generated 'JSON', such as how Gemini 2.0 doesn't reliably escape quotes in strings.

## dumps

```python
def dumps(obj, indent=None)
```

Serialize an object to a JSON string

# quiq.jwt

## get\_unverified\_claimset

```python
def get_unverified_claimset(encoded)
```

Read the claimset of a JWT without validating its signature

**Arguments**:

* `encoded` - the encoded JWT

**Returns**:

Claims dictionary

## get\_unverified\_headers

```python
def get_unverified_headers(encoded)
```

Read the headers of a JWT without validating its signature

**Arguments**:

* `encoded` - the encoded JWT

**Returns**:

Headers dictionary

# quiq.random

## choice

```python
def choice(seq)
```

Return a random element from the non-empty sequence seq.

# quiq.re

Wrappers around commonly used regex functions

## findall

```python
def findall(pattern, string, ignore_case=False)
```

Find all occurences of a regex pattern in a string

## sub

```python
def sub(pattern, repl, string, count=0, ignore_case=False)
```

Substitute occurences of a regex pattern in a string with a replacement

# quiq.strings

## levenshtein\_distance

```python
def levenshtein_distance(string1, string2)
```

Compute the levenshtein edit distance between two strings

**Returns**:

The edit distance as an int

# quiq.tokens

## count

```python
def count(llm, prompt)
```

Count the tokens used by the specified prompt. Only works for OpenAI ChatCompletion models that use the cl100k\_base encoder.

# quiq.urllib.parse

## quote

```python
def quote(string, safe='/', encoding=None, errors=None)
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote>

## quote\_plus

```python
def quote_plus(string, safe='', encoding=None, errors=None)
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote_plus>

## unquote

```python
def unquote(string, encoding='utf-8', errors='replace')
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote>

## unquote\_plus

```python
def unquote_plus(string, encoding='utf-8', errors='replace')
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote_plus>

## urlparse

```python
def urlparse(urlstring, scheme='', allow_fragments=True)
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlparse>

## urlunparse

```python
def urlunparse(parts)
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlunparse>

## urlencode

```python
def urlencode(query,
              doseq=False,
              safe='',
              encoding=None,
              errors=None,
              quote_via=quote_plus)
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlencode>

## parse\_qs

```python
def parse_qs(qs,
             keep_blank_values=False,
             strict_parsing=False,
             encoding='utf-8',
             errors='replace',
             max_num_fields=None,
             separator='&')
```

<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.parse_qs>

# quiq.yaml

## safe\_load

```python
def safe_load(data)
```

Deserialize YAML into an object

## dump

```python
def dump(data)
```

Serialize an object to YAML