Metadata-Version: 2.4
Name: redis-agent-playbook
Version: 0.1.0a1
Summary: Python Client SDK for Redis Playbook Service
License: MIT
License-File: LICENSE
Author: Redis AI Services Team
Requires-Python: >=3.10
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Dist: httpcore (>=1.0.9)
Requires-Dist: httpx (>=0.28.1)
Requires-Dist: pydantic (>=2.11.2)
Project-URL: Documentation, https://pypi.org/project/redis-agent-playbook/
Project-URL: Homepage, https://redis.io/docs/latest/develop/ai/
Description-Content-Type: text/markdown

# redis-agent-playbook

Developer-friendly & type-safe Python SDK specifically catered to leverage *redis-agent-playbook* API.

[![Built by Speakeasy](https://img.shields.io/badge/Built_by-SPEAKEASY-374151?style=for-the-badge&labelColor=f3f4f6)](https://www.speakeasy.com/?utm_source=redis-agent-playbook&utm_campaign=python)
[![License: MIT](https://img.shields.io/badge/LICENSE_//_MIT-3b5bdb?style=for-the-badge&labelColor=eff6ff)](https://opensource.org/licenses/MIT)

<!-- Start Summary [summary] -->
## Summary

Redis Playbook: Public type-specific FAQ and Skill authoring, publication, and exact-version API.

For more information about the API: [Redis AI documentation](https://redis.io/docs/latest/develop/ai/)
<!-- End Summary [summary] -->

## Documentation

- [Redis AI documentation](https://redis.io/docs/latest/develop/ai/)
- [PyPI package page](https://pypi.org/project/redis-agent-playbook/)
- Generated operation and model reference is included below on this package page.

Dedicated Playbook product guides are required before a stable release. Until
then, this alpha package and its generated reference are the SDK documentation.

## Release status

This SDK is an alpha prerelease. Breaking changes may land between alpha
releases without a major-version increment. Install prereleases explicitly:

```bash
pip install --pre redis-agent-playbook
```

Pin an exact published version in applications and upgrade intentionally.

<!-- Start Table of Contents [toc] -->
## Table of Contents
<!-- $toc-max-depth=2 -->
* [redis-agent-playbook](#redis-agent-playbook)
  * [Documentation](#documentation)
  * [Release status](#release-status)
  * [SDK Installation](#sdk-installation)
  * [IDE Support](#ide-support)
  * [SDK Example Usage](#sdk-example-usage)
  * [Common workflows](#common-workflows)
  * [Authentication](#authentication)
  * [Available Resources and Operations](#available-resources-and-operations)
  * [Global Parameters](#global-parameters)
  * [Retries](#retries)
  * [Error Handling](#error-handling)
  * [Custom HTTP Client](#custom-http-client)
  * [Resource Management](#resource-management)
  * [Debugging](#debugging)
* [Development](#development)
  * [Maturity](#maturity)
  * [Contributions](#contributions)

<!-- End Table of Contents [toc] -->

<!-- Start SDK Installation [installation] -->
## SDK Installation

> [!NOTE]
> **Python version upgrade policy**
>
> Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.

The SDK can be installed with *uv*, *pip*, or *poetry* package managers.

### uv

*uv* is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.

```bash
uv add redis-agent-playbook
```

### PIP

*PIP* is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.

```bash
pip install redis-agent-playbook
```

### Poetry

*Poetry* is a modern tool that simplifies dependency management and package publishing by using a single `pyproject.toml` file to handle project metadata and dependencies.

```bash
poetry add redis-agent-playbook
```

### Shell and script usage with `uv`

You can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so:

```shell
uvx --from redis-agent-playbook python
```

It's also possible to write a standalone Python script without needing to set up a whole project like so:

```python
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "redis-agent-playbook",
# ]
# ///

from redis_agent_playbook import Playbook

sdk = Playbook(
  # SDK arguments
)

# Rest of script here...
```

Once that is saved to a file, you can run it with `uv run script.py` where
`script.py` can be replaced with the actual file name.
<!-- End SDK Installation [installation] -->

<!-- Start IDE Support [idesupport] -->
## IDE Support

### PyCharm

Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.

- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/)
<!-- End IDE Support [idesupport] -->

<!-- Start SDK Example Usage [usage] -->
## SDK Example Usage

### Create an FAQ

Create the first immutable version of a customer-support FAQ. The returned entry is an unpublished draft.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.create_faq(content={
        "intents": [
            "Where is my refund?",
            "Refund still processing",
        ],
        "attributes": {
            "audience": "support",
            "locale": "en-US",
            "topic": "refund",
        },
        "metadata": {
            "sourceId": "support-refund-policy-v4",
            "status": "approved",
        },
        "payload": {
            "faq": {
                "question": "How can support check the status of an in-flight refund?",
                "answer": "Look up the refund by order ID, share its current stage and date, and do not promise a bank posting date.",
            },
        },
    }, entry_key="refund-status-check")

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.create_faq_async(content={
            "intents": [
                "Where is my refund?",
                "Refund still processing",
            ],
            "attributes": {
                "audience": "support",
                "locale": "en-US",
                "topic": "refund",
            },
            "metadata": {
                "sourceId": "support-refund-policy-v4",
                "status": "approved",
            },
            "payload": {
                "faq": {
                    "question": "How can support check the status of an in-flight refund?",
                    "answer": "Look up the refund by order ID, share its current stage and date, and do not promise a bank posting date.",
                },
            },
        }, entry_key="refund-status-check")

        # Handle response
        print(res)

asyncio.run(main())
```

### Add an FAQ version

Append an immutable version to an existing FAQ. Replace the example ID with the entry ID returned by `create_faq`.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.append_faq_version(faq_id="ent_0123456789abcdef0123456789abcdef", content={
        "intents": [
            "Where is my refund?",
            "Check refund progress",
        ],
        "attributes": {
            "audience": "support",
            "locale": "en-US",
            "topic": "refund",
        },
        "metadata": {
            "sourceId": "support-refund-policy-v5",
            "status": "approved",
        },
        "payload": {
            "faq": {
                "question": "How can support check the status of an in-flight refund?",
                "answer": "Look up the refund by order ID and share its current stage and date. Card refunds normally post 5 to 10 business days after warehouse receipt.",
            },
        },
    })

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.append_faq_version_async(faq_id="ent_0123456789abcdef0123456789abcdef", content={
            "intents": [
                "Where is my refund?",
                "Check refund progress",
            ],
            "attributes": {
                "audience": "support",
                "locale": "en-US",
                "topic": "refund",
            },
            "metadata": {
                "sourceId": "support-refund-policy-v5",
                "status": "approved",
            },
            "payload": {
                "faq": {
                    "question": "How can support check the status of an in-flight refund?",
                    "answer": "Look up the refund by order ID and share its current stage and date. Card refunds normally post 5 to 10 business days after warehouse receipt.",
                },
            },
        })

        # Handle response
        print(res)

asyncio.run(main())
```

### Publish an FAQ version

Publish the selected immutable FAQ version so it can be returned by search and discovery.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.publish_faq(faq_id="ent_0123456789abcdef0123456789abcdef", version=2)

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.publish_faq_async(faq_id="ent_0123456789abcdef0123456789abcdef", version=2)

        # Handle response
        print(res)

asyncio.run(main())
```

### Create a Skill

Create an unpublished Skill from a base64-encoded Agent Skills ZIP. Replace the package placeholder with an encoded archive rooted at `late-delivery-resolution/` and containing `SKILL.md`.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.create_skill(package_base64="BASE64_ENCODED_AGENT_SKILL_ZIP", content={
        "intents": [
            "Resolve a late delivery",
            "Package has not arrived",
        ],
        "attributes": {
            "audience": "support",
            "locale": "en-US",
            "topic": "delivery",
        },
        "metadata": {
            "sourceId": "runbook-late-delivery-v1",
            "status": "approved",
        },
    }, entry_key="late-delivery-resolution")

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.create_skill_async(package_base64="BASE64_ENCODED_AGENT_SKILL_ZIP", content={
            "intents": [
                "Resolve a late delivery",
                "Package has not arrived",
            ],
            "attributes": {
                "audience": "support",
                "locale": "en-US",
                "topic": "delivery",
            },
            "metadata": {
                "sourceId": "runbook-late-delivery-v1",
                "status": "approved",
            },
        }, entry_key="late-delivery-resolution")

        # Handle response
        print(res)

asyncio.run(main())
```

### Search FAQs

Search only published FAQs, restrict results to exact-match attributes, and override the similarity threshold for this request.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.search_faqs(query="Where is my refund?", filter_={
        "and_": [
            {
                "eq": {
                    "name": "audience",
                    "value": "support",
                },
            },
            {
                "eq": {
                    "name": "locale",
                    "value": "en-US",
                },
            },
        ],
    }, minimum_score=0.72, limit=5)

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.search_faqs_async(query="Where is my refund?", filter_={
            "and_": [
                {
                    "eq": {
                        "name": "audience",
                        "value": "support",
                    },
                },
                {
                    "eq": {
                        "name": "locale",
                        "value": "en-US",
                    },
                },
            ],
        }, minimum_score=0.72, limit=5)

        # Handle response
        print(res)

asyncio.run(main())
```

### Search Skills

Search only published Skills. Skill matches contain compact previews with canonical exact-version `SKILL.md` URIs.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.search_skills(query="How should I resolve a delayed delivery?", filter_={
        "eq": {
            "name": "audience",
            "value": "support",
        },
    }, minimum_score=0.72, limit=5)

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.search_skills_async(query="How should I resolve a delayed delivery?", filter_={
            "eq": {
                "name": "audience",
                "value": "support",
            },
        }, minimum_score=0.72, limit=5)

        # Handle response
        print(res)

asyncio.run(main())
```

### Discover Playbook entries

Search published FAQs and Skills together while pinning a known Skill by its immutable entry key. Pins are returned separately from semantic matches.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.discover_entries(query="A customer's order is late and they want a refund", filter_={
        "eq": {
            "name": "audience",
            "value": "support",
        },
    }, limit=10, pinned_entries=[
        {
            "entry_key": "late-delivery-resolution",
        },
    ])

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.discover_entries_async(query="A customer's order is late and they want a refund", filter_={
            "eq": {
                "name": "audience",
                "value": "support",
            },
        }, limit=10, pinned_entries=[
            {
                "entry_key": "late-delivery-resolution",
            },
        ])

        # Handle response
        print(res)

asyncio.run(main())
```

### Create a proposal

Propose a new FAQ for review. Launch proposal authoring supports new FAQ entries.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.create_proposal(action={
        "add": {
            "target": {
                "new_entry": {
                    "entry_key": "refund-bank-delay",
                },
            },
            "candidate": {
                "content": {
                    "intents": [
                        "My refund has not appeared",
                    ],
                    "attributes": {
                        "audience": "support",
                        "locale": "en-US",
                        "topic": "refund",
                    },
                    "metadata": {
                        "sourceId": "support-refund-policy-v5",
                        "status": "proposed",
                    },
                    "payload": {
                        "faq": {
                            "question": "What should support say when a settled refund has not appeared?",
                            "answer": "Confirm the settlement date and explain that the issuing bank controls final posting time.",
                        },
                    },
                },
            },
        },
    }, support_id="sup_0123456789abcdef0123456789abcdef")

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.create_proposal_async(action={
            "add": {
                "target": {
                    "new_entry": {
                        "entry_key": "refund-bank-delay",
                    },
                },
                "candidate": {
                    "content": {
                        "intents": [
                            "My refund has not appeared",
                        ],
                        "attributes": {
                            "audience": "support",
                            "locale": "en-US",
                            "topic": "refund",
                        },
                        "metadata": {
                            "sourceId": "support-refund-policy-v5",
                            "status": "proposed",
                        },
                        "payload": {
                            "faq": {
                                "question": "What should support say when a settled refund has not appeared?",
                                "answer": "Confirm the settlement date and explain that the issuing bank controls final posting time.",
                            },
                        },
                    },
                },
            },
        }, support_id="sup_0123456789abcdef0123456789abcdef")

        # Handle response
        print(res)

asyncio.run(main())
```

### Accept a proposal

Promote the reviewed revision to one canonical unpublished FAQ. Concurrent calls and retries resume or return the recorded target.

```python
# Synchronous Example
from redis_agent_playbook import Playbook


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.accept_proposal(proposal_id="prp_0123456789abcdef0123456789abcdef", expected_proposal_revision=1)

    # Handle response
    print(res)
```

</br>

The same SDK client can also be used to make asynchronous requests by importing asyncio.

```python
# Asynchronous Example
import asyncio
from redis_agent_playbook import Playbook

async def main():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:

        res = await playbook.accept_proposal_async(proposal_id="prp_0123456789abcdef0123456789abcdef", expected_proposal_revision=1)

        # Handle response
        print(res)

asyncio.run(main())
```
<!-- End SDK Example Usage [usage] -->

## Common workflows

Playbook stores two entry types: FAQs and Skills. Creating or appending content
produces an immutable version; publishing selects which version is available to
search and discovery. Management reads can still retrieve unpublished entries
and exact historical versions.

The examples below use fictional Northstar customer-support content. They are
maintained outside the generated section above so they can show IDs and version
numbers flowing between multiple SDK calls.

### Create, version, publish, and read an FAQ

`create_faq` returns both the stable entry and version 1. Append creates another
immutable version; it does not publish it automatically.

```python
from redis_agent_playbook import Playbook


faq_v1 = {
    "intents": ["Where is my refund?", "Refund still processing"],
    "attributes": {
        "audience": "support",
        "locale": "en-US",
        "topic": "refund",
    },
    "metadata": {"sourceId": "support-refund-policy-v4", "status": "approved"},
    "payload": {
        "faq": {
            "question": "How can support check an in-flight refund?",
            "answer": "Look up the refund by order ID and share its stage and date.",
        }
    },
}

with Playbook(
    "https://api.example.com",
    playbook_id="<playbook-id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:
    created = playbook.create_faq(
        entry_key="refund-status-check",
        content=faq_v1,
    )
    faq_id = created.entry.entry_id

    appended = playbook.append_faq_version(
        faq_id=faq_id,
        content={
            **faq_v1,
            "metadata": {
                "sourceId": "support-refund-policy-v5",
                "status": "approved",
            },
            "payload": {
                "faq": {
                    "question": "How can support check an in-flight refund?",
                    "answer": (
                        "Share the current stage and date. Card refunds normally "
                        "post 5 to 10 business days after warehouse receipt."
                    ),
                }
            },
        },
    )

    playbook.publish_faq(
        faq_id=faq_id,
        version=appended.version.version,
    )

    entry = playbook.get_faq(faq_id=faq_id)
    exact_version = playbook.get_faq_version(
        faq_id=faq_id,
        version=appended.version.version,
    )
    entries = playbook.list_faqs(published=True, limit=20)
    versions = playbook.list_faq_versions(faq_id=faq_id, limit=20)

    print(entry.publication.version)
    print(exact_version.content.payload.faq.answer)
    print([item.entry_key for item in entries.faqs])
    print([item.version for item in versions.versions])
```

Continue a list request with its `next_cursor` until that field is absent. List
results are not a global snapshot, so concurrent writes can move entries between
pages.

### Create and version a Skill

An Agent Skills package is a ZIP rooted at the Skill name and containing
`SKILL.md`, for example `late-delivery-resolution/SKILL.md`. Encode the complete
ZIP as base64; do not base64-encode the individual files.

```python
import base64
from pathlib import Path

from redis_agent_playbook import Playbook


def encode_skill(path: str) -> str:
    return base64.b64encode(Path(path).read_bytes()).decode("ascii")


with Playbook(
    "https://api.example.com",
    playbook_id="<playbook-id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:
    created = playbook.create_skill(
        entry_key="late-delivery-resolution",
        package_base64=encode_skill("late-delivery-resolution-v1.zip"),
        content={
            "intents": ["Resolve a late delivery", "Package has not arrived"],
            "attributes": {
                "audience": "support",
                "locale": "en-US",
                "topic": "delivery",
            },
            "metadata": {
                "sourceId": "runbook-late-delivery-v1",
                "status": "approved",
            },
        },
    )
    skill_id = created.entry.entry_id

    appended = playbook.append_skill_version(
        skill_id=skill_id,
        package_base64=encode_skill("late-delivery-resolution-v2.zip"),
        content={
            "intents": ["Resolve a late delivery", "Escalate conflicting tracking"],
            "attributes": {
                "audience": "support",
                "locale": "en-US",
                "topic": "delivery",
            },
            "metadata": {
                "sourceId": "runbook-late-delivery-v2",
                "status": "approved",
            },
        },
    )
    playbook.publish_skill(
        skill_id=skill_id,
        version=appended.version.version,
    )

    entry = playbook.get_skill(skill_id=skill_id)
    exact_version = playbook.get_skill_version(
        skill_id=skill_id,
        version=appended.version.version,
    )
    entries = playbook.list_skills(published=True, limit=20)
    versions = playbook.list_skill_versions(skill_id=skill_id, limit=20)

    print(entry.publication.version)
    print(exact_version.content.payload.skill.manifest.name)
    print([item.entry_key for item in entries.skills])
    print([item.version for item in versions.versions])
```

### Search FAQs, search Skills, and discover across both

Type-specific search returns only published entries of that type. Discovery
searches published FAQs and Skills together. Filters match authored `attributes`
exactly; metadata is returned to callers but is not the filter namespace.

```python
from redis_agent_playbook import Playbook


support_filter = {
    "and_": [
        {"eq": {"name": "audience", "value": "support"}},
        {"eq": {"name": "locale", "value": "en-US"}},
    ]
}

with Playbook(
    "https://api.example.com",
    playbook_id="<playbook-id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:
    faq_results = playbook.search_faqs(
        query="Where is my refund?",
        filter_=support_filter,
        minimum_score=0.72,
        limit=5,
    )
    skill_results = playbook.search_skills(
        query="How should I resolve a delayed delivery?",
        filter_=support_filter,
        minimum_score=0.72,
        limit=5,
    )

    # Use the Playbook policy defaults for ranking, thresholds, and result count.
    default_discovery = playbook.discover_entries(
        query="A customer's order is late and they want a refund",
    )

    # Override this request and guarantee that a known Skill is supplied to the caller.
    guided_discovery = playbook.discover_entries(
        query="A customer's order is late and they want a refund",
        filter_=support_filter,
        limit=10,
        pinned_entries=[{"entry_key": "late-delivery-resolution"}],
    )

    print([match.faq.question for match in faq_results.matches])
    print([match.skill.name for match in skill_results.matches])
    print(default_discovery.discovered_entries)
    print(guided_discovery.pinned_entries)
```

Pinned entries are resolved separately from semantic matches. Check `truncated`
when more eligible candidates existed than result slots, and
`budget_truncated` when the Playbook token budget prevented an otherwise
eligible entry from being returned.

### Manage and accept proposals

Proposal replacement uses optimistic concurrency. Read `proposal_revision`,
review the complete candidate, and pass that revision to `replace_proposal` or
`accept_proposal`. A conflict means another writer changed the proposal and the
caller should fetch it again before deciding what to do.

```python
from redis_agent_playbook import Playbook, models


def proposed_faq(answer: str) -> dict:
    return {
        "add": {
            "target": {"new_entry": {"entry_key": "refund-bank-delay"}},
            "candidate": {
                "content": {
                    "intents": ["My refund has not appeared"],
                    "attributes": {
                        "audience": "support",
                        "locale": "en-US",
                        "topic": "refund",
                    },
                    "metadata": {
                        "sourceId": "support-refund-policy-v5",
                        "status": "proposed",
                    },
                    "payload": {
                        "faq": {
                            "question": (
                                "What should support say when a settled refund "
                                "has not appeared?"
                            ),
                            "answer": answer,
                        }
                    },
                }
            },
        }
    }


with Playbook(
    "https://api.example.com",
    playbook_id="<playbook-id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:
    created = playbook.create_proposal(
        action=proposed_faq("Explain that the issuing bank controls posting time."),
        support_id="sup_0123456789abcdef0123456789abcdef",
    )
    proposal_id = created.proposal_id

    inbox = playbook.list_proposals(view=models.ProposalView.INBOX, limit=20)
    matches = playbook.search_proposals(query="refund posting delay", limit=5)
    reviewed = playbook.get_proposal(proposal_id=proposal_id)

    replaced = playbook.replace_proposal(
        proposal_id=proposal_id,
        expected_proposal_revision=reviewed.proposal_revision,
        action=proposed_faq(
            "Confirm the settlement date and explain that the issuing bank "
            "controls final posting time."
        ),
    )

    # Dismissal and restoration move a proposal between inbox and trash.
    dismissed = playbook.dismiss_proposal(
        proposal_id=proposal_id,
        expected_proposal_revision=replaced.proposal_revision,
    )
    restored = playbook.restore_proposal(proposal_id=proposal_id)

    # Acceptance promotes the reviewed revision to one canonical unpublished FAQ.
    accepted = playbook.accept_proposal(
        proposal_id=proposal_id,
        expected_proposal_revision=restored.proposal_revision,
    )
    playbook.publish_faq(
        faq_id=accepted.entry.entry_id,
        version=accepted.version.version,
    )

    print(len(inbox.proposals), len(matches.matches))

    # Purge is the permanent-delete operation. Use it only when the proposal
    # record is no longer required; it does not delete an FAQ already accepted.
    playbook.purge_proposal(proposal_id=proposal_id)
```

Proposal acceptance records one canonical target and is safe to retry with
bounded backoff. Concurrent calls and retries resume the same promotion or
return its existing unpublished FAQ; publish that returned version separately
when it is ready for serving.

<!-- Start Authentication [security] -->
## Authentication

### Per-Client Security Schemes

This SDK supports the following security scheme globally:

| Name      | Type | Scheme      | Environment Variable |
| --------- | ---- | ----------- | -------------------- |
| `api_key` | http | HTTP Bearer | `PLAYBOOK_API_KEY`   |

To authenticate with the API the `api_key` parameter must be set when initializing the SDK client instance. For example:
```python
from redis_agent_playbook import Playbook, models


with Playbook(
    "https://api.example.com",
    api_key="<PLAYBOOK_API_KEY>",
    playbook_id="<id>",
) as playbook:

    res = playbook.clear_playbook(scope=models.ClearScope.ALL)

    # Handle response
    print(res)

```
<!-- End Authentication [security] -->

<!-- Start Available Resources and Operations [operations] -->
## Available Resources and Operations

<details open>
<summary>Available methods</summary>

### Playbook SDK

* clear_playbook
* discover_entries
* lookup_entries - Resolves bounded entry references to compact management state. Results preserve input order and report misses explicitly. Each item is authoritative when read, but the batch is not a global snapshot.
* delete_faqs - Deletes the requested FAQ families sequentially. Each family deletion is atomic, but the batch is not: deletions completed before an error remain applied. Retrying the same request is safe because already absent entries are ignored.
* list_faqs
* create_faq
* search_faqs
* delete_faq
* get_faq
* withdraw_faq - Withdraws the FAQ publication without changing version content. An already-unpublished entry is a no-op. Concurrent publication changes are last-write-wins in Playbook v1.
* publish_faq - Publishes the selected immutable FAQ version. Repeating the currently published version is a no-op. Concurrent publication changes are last-write-wins in Playbook v1.
* list_faq_versions
* append_faq_version
* get_faq_version
* get_playbook_health
* list_proposals
* create_proposal
* search_proposals
* purge_proposal
* get_proposal
* replace_proposal
* accept_proposal - Promotes the reviewed revision to one canonical unpublished FAQ.
Concurrent calls and retries resume or return the proposal's recorded target.
A complete target may be visible to management before the proposal reaches
promoted, but remains absent from serving until separately published.
* restore_proposal
* dismiss_proposal
* add_proposal_support
* delete_skills - Deletes the requested Skill families sequentially. Each family deletion is atomic, but the batch is not: deletions completed before an error remain applied. Retrying the same request is safe because already absent entries are ignored.
* list_skills
* create_skill
* search_skills
* delete_skill
* get_skill
* withdraw_skill - Withdraws the Skill publication without changing version content. An already-unpublished entry is a no-op. Concurrent publication changes are last-write-wins in Playbook v1.
* publish_skill - Publishes the selected immutable Skill version. Repeating the currently published version is a no-op. Concurrent publication changes are last-write-wins in Playbook v1.
* list_skill_versions
* append_skill_version
* get_skill_version
* get_skill_resource - Returns the exact immutable Skill resource bytes as a streamed response.

Every successful resource read includes a required `Content-Digest` response
header. Header names are case-insensitive. The header uses the RFC 9530
`sha-256=:<base64>:` representation, while the resource descriptor in the
Skill version uses `sha256:<lowercase-hex>`. Both encode the same SHA-256
digest bytes and must not be compared as strings.


</details>
<!-- End Available Resources and Operations [operations] -->

<!-- Start Global Parameters [global-parameters] -->
## Global Parameters

A parameter is configured globally. This parameter may be set on the SDK client instance itself during initialization. When configured as an option during SDK initialization, This global value will be used as the default on the operations that use it. When such operations are called, there is a place in each to override the global value, if needed.

For example, you can set `playbookId` to `"<id>"` at SDK initialization and then you do not have to pass the same value on calls to operations like `clear_playbook`. But if you want to do so you may, which will locally override the global setting. See the example code below for a demonstration.


### Available Globals

The following global parameter is available.
Global parameters can also be set via environment variable.

| Name        | Type | Description                | Environment          |
| ----------- | ---- | -------------------------- | -------------------- |
| playbook_id | str  | The playbook_id parameter. | PLAYBOOK_PLAYBOOK_ID |

### Example

```python
from redis_agent_playbook import Playbook, models


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.clear_playbook(scope=models.ClearScope.ALL)

    # Handle response
    print(res)

```
<!-- End Global Parameters [global-parameters] -->

<!-- Start Retries [retries] -->
## Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call:
```python
from redis_agent_playbook import Playbook, models
from redis_agent_playbook.utils import BackoffStrategy, RetryConfig


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.clear_playbook(scope=models.ClearScope.ALL,
        RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))

    # Handle response
    print(res)

```

If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK:
```python
from redis_agent_playbook import Playbook, models
from redis_agent_playbook.utils import BackoffStrategy, RetryConfig


with Playbook(
    "https://api.example.com",
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:

    res = playbook.clear_playbook(scope=models.ClearScope.ALL)

    # Handle response
    print(res)

```
<!-- End Retries [retries] -->

<!-- Start Error Handling [errors] -->
## Error Handling

`PlaybookError` is the base class for all HTTP error responses. It has the following properties:

| Property           | Type             | Description                                                                             |
| ------------------ | ---------------- | --------------------------------------------------------------------------------------- |
| `err.message`      | `str`            | Error message                                                                           |
| `err.status_code`  | `int`            | HTTP response status code eg `404`                                                      |
| `err.headers`      | `httpx.Headers`  | HTTP response headers                                                                   |
| `err.body`         | `str`            | HTTP body. Can be empty string if no body is returned.                                  |
| `err.raw_response` | `httpx.Response` | Raw HTTP response                                                                       |
| `err.data`         |                  | Optional. Some errors may contain structured data. [See Error Classes](#error-classes). |

### Example
```python
from redis_agent_playbook import Playbook, errors, models


with Playbook(
    "https://api.example.com",
    playbook_id="<id>",
    api_key="<PLAYBOOK_API_KEY>",
) as playbook:
    res = None
    try:

        res = playbook.clear_playbook(scope=models.ClearScope.ALL)

        # Handle response
        print(res)


    except errors.PlaybookError as e:
        # The base class for HTTP error responses
        print(e.message)
        print(e.status_code)
        print(e.body)
        print(e.headers)
        print(e.raw_response)

        # Depending on the method different errors may be thrown
        if isinstance(e, errors.RequestValidationErrorResponseContent):
            print(e.data.title)  # str
            print(e.data.status)  # Optional[int]
            print(e.data.detail)  # Optional[str]
            print(e.data.instance)  # Optional[str]
            print(e.data.type)  # models.RequestValidationErrorType
```

### Error Classes
**Primary errors:**
* `PlaybookError`: The base class for HTTP error responses.
  * `RequestValidationErrorResponseContent`: One HTTP 400 schema preserves every validation problem type in generated clients. Status code `400`.
  * `AuthenticationErrorResponseContent`: Authentication credentials are missing, malformed, or invalid. Status code `401`.
  * `ForbiddenErrorResponseContent`: The caller is authenticated but not allowed to access the requested resource. Status code `403`.
  * `NotFoundErrorResponseContent`: The requested resource does not exist. Status code `404`.
  * `TimeoutErrorResponseContent`: The request timed out before the service could complete it. Status code `408`.
  * `PlaybookConflictErrorResponseContent`: One schema per HTTP status preserves the complete problem catalog in generated clients, following the Iris/Agent Memory dedicated error-type enum pattern. Status code `409`.
  * `PayloadTooLargeErrorResponseContent`: The request payload exceeds the maximum supported size. Status code `413`.
  * `ResourceSuspendedErrorResponseContent`: The requested resource exists but is suspended by an administrator. Status code `423`.
  * `FailedDependencyErrorResponseContent`: A dependent resource required to process the request is unavailable or unhealthy. Status code `424`.
  * `TooManyRequestsErrorResponseContent`: The service rejected the request because rate limits were exceeded. Status code `429`.
  * `PlaybookInternalErrorResponseContent`: Stored integrity failures require operator investigation; editing or blindly retrying the request does not repair the stored record. Status code `500`.
  * `PlaybookServiceUnavailableErrorResponseContent`: Retry reads and proposal acceptance with bounded backoff. Acceptance resumes its recorded canonical target. An uncertain create or append response may have written another logical record or version and should not be blindly retried when the caller requires exactly one result. Status code `503`.

<details><summary>Less common errors (5)</summary>

<br />

**Network errors:**
* [`httpx.RequestError`](https://www.python-httpx.org/exceptions/#httpx.RequestError): Base class for request errors.
    * [`httpx.ConnectError`](https://www.python-httpx.org/exceptions/#httpx.ConnectError): HTTP client was unable to make a request to a server.
    * [`httpx.TimeoutException`](https://www.python-httpx.org/exceptions/#httpx.TimeoutException): HTTP request timed out.


**Inherit from `PlaybookError`**:
* `ResponseValidationError`: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the `cause` attribute.

</details>
<!-- End Error Handling [errors] -->

<!-- Start Custom HTTP Client [http-client] -->
## Custom HTTP Client

The Python SDK makes API calls using the [httpx](https://www.python-httpx.org/) HTTP library.  In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.
Depending on whether you are using the sync or async version of the SDK, you can pass an instance of `HttpClient` or `AsyncHttpClient` respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.
This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of `httpx.Client` or `httpx.AsyncClient` directly.

For example, you could specify a header for every request that this sdk makes as follows:
```python
from redis_agent_playbook import Playbook
import httpx

http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = Playbook(client=http_client)
```

or you could wrap the client with your own custom logic:
```python
from redis_agent_playbook import Playbook
from redis_agent_playbook.httpclient import AsyncHttpClient
import httpx

class CustomClient(AsyncHttpClient):
    client: AsyncHttpClient

    def __init__(self, client: AsyncHttpClient):
        self.client = client

    async def send(
        self,
        request: httpx.Request,
        *,
        stream: bool = False,
        auth: Union[
            httpx._types.AuthTypes, httpx._client.UseClientDefault, None
        ] = httpx.USE_CLIENT_DEFAULT,
        follow_redirects: Union[
            bool, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
    ) -> httpx.Response:
        request.headers["Client-Level-Header"] = "added by client"

        return await self.client.send(
            request, stream=stream, auth=auth, follow_redirects=follow_redirects
        )

    def build_request(
        self,
        method: str,
        url: httpx._types.URLTypes,
        *,
        content: Optional[httpx._types.RequestContent] = None,
        data: Optional[httpx._types.RequestData] = None,
        files: Optional[httpx._types.RequestFiles] = None,
        json: Optional[Any] = None,
        params: Optional[httpx._types.QueryParamTypes] = None,
        headers: Optional[httpx._types.HeaderTypes] = None,
        cookies: Optional[httpx._types.CookieTypes] = None,
        timeout: Union[
            httpx._types.TimeoutTypes, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
        extensions: Optional[httpx._types.RequestExtensions] = None,
    ) -> httpx.Request:
        return self.client.build_request(
            method,
            url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            cookies=cookies,
            timeout=timeout,
            extensions=extensions,
        )

s = Playbook(async_client=CustomClient(httpx.AsyncClient()))
```
### httpx2 (Pydantic's httpx fork)

[httpx2](https://httpx2.pydantic.dev/) is Pydantic's maintained fork of `httpx`. To run this SDK on httpx2, call `alias_httpx()` at your program's entry point, before importing the SDK, so every `import httpx` — including the ones inside the SDK — resolves to `httpx2`:
```python
import httpx2

httpx2.alias_httpx()

from redis_agent_playbook import Playbook

s = Playbook()
```

An SDK can also be generated against httpx2 directly, so it depends on the fork instead of `httpx`, by setting `python.httpClientLibrary: httpx2` in `gen.yaml`.
<!-- End Custom HTTP Client [http-client] -->

<!-- Start Resource Management [resource-management] -->
## Resource Management

The `Playbook` class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a [context manager][context-manager] and reuse it across the application.

[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers

```python
from redis_agent_playbook import Playbook
def main():

    with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:
        # Rest of application here...


# Or when using async:
async def amain():

    async with Playbook(
        "https://api.example.com",
        playbook_id="<id>",
        api_key="<PLAYBOOK_API_KEY>",
    ) as playbook:
        # Rest of application here...
```
<!-- End Resource Management [resource-management] -->

<!-- Start Debugging [debug] -->
## Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.
```python
from redis_agent_playbook import Playbook
import logging

logging.basicConfig(level=logging.DEBUG)
s = Playbook(server_url="https://example.com", debug_logger=logging.getLogger("redis_agent_playbook"))
```

You can also enable a default debug logger by setting an environment variable `PLAYBOOK_DEBUG` to true.
<!-- End Debugging [debug] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->

# Development

## Maturity

This SDK is an alpha prerelease. Breaking changes may occur between prerelease
versions without a major-version increment. Pin an exact package version so
upgrades are intentional, and use prerelease installation flags when resolving
the latest alpha.

## Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation.
We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

### SDK Created by [Speakeasy](https://www.speakeasy.com/?utm_source=redis-agent-playbook&utm_campaign=python)

