Skip to content

Document Writer

FoxNoseWriter writes LangChain Document objects into a FoxNose collection through the Flux write API. Each document becomes one FoxNose resource, published immediately.

It is the write counterpart to FoxNoseRetriever and FoxNoseLoader. Requires foxnose-sdk>=0.8.1.

Quick Start

from foxnose_sdk.flux import FluxClient
from foxnose_sdk.auth import SimpleKeyAuth
from langchain_core.documents import Document
from langchain_foxnose import FoxNoseWriter

client = FluxClient(
    base_url="https://<env_key>.fxns.io",
    api_prefix="my_api",
    auth=SimpleKeyAuth("YOUR_PUBLIC_KEY", "YOUR_SECRET_KEY"),
)

writer = FoxNoseWriter(
    client=client,
    collection_path="knowledge-base",
    page_content_field="body",
)

keys = writer.add_documents([
    Document(page_content="FoxNose is the knowledge layer for RAG.",
             metadata={"title": "What is FoxNose?"}),
])
print(keys)  # ['<resource_key>']

page_content goes into page_content_field; everything in metadata becomes a sibling data field.

Convenience Constructor

writer = FoxNoseWriter.from_client_params(
    base_url="https://<env_key>.fxns.io",
    api_prefix="my_api",
    auth=SimpleKeyAuth("YOUR_PUBLIC_KEY", "YOUR_SECRET_KEY"),
    collection_path="knowledge-base",
    page_content_field="body",
)

Updating

update_document takes the internal resource key — the value add_documents returned, or doc.metadata["key"] on a document you read back.

revision = writer.update_document(keys[0], Document(
    page_content="FoxNose is the knowledge layer for RAG. Updated.",
    metadata={"title": "What is FoxNose?"},
))

Update is a full replace, not a merge

Fields absent from the mapped data are removed from the stored resource. If you want to change one field, read the document first, edit it, and write the whole thing back — see Round-tripping.

Async

import asyncio
from foxnose_sdk.flux import AsyncFluxClient

async def main():
    async_client = AsyncFluxClient(
        base_url="https://<env_key>.fxns.io",
        api_prefix="my_api",
        auth=SimpleKeyAuth("pk", "sk"),
    )
    writer = FoxNoseWriter(
        async_client=async_client,
        collection_path="knowledge-base",
        page_content_field="body",
    )
    keys = await writer.aadd_documents([Document(page_content="Hello")])
    await writer.aupdate_document(keys[0], Document(page_content="Hello again"))
    await async_client.aclose()

asyncio.run(main())

There is no concurrency option, on purpose

Both add_documents and aadd_documents write sequentially and stop at the first failure. Flux writes are non-idempotent, the SDK never retries them, and Flux has no delete endpoint — so overlapping them would make it impossible to report which documents were attempted. If you want concurrency, chunk the input and drive aadd_documents yourself, accepting that ambiguity.

Deduplication with external_id_key

Point external_id_key at a metadata key holding your own stable identifier. Its value is sent as the resource key and is not written into data:

writer = FoxNoseWriter(
    client=client,
    collection_path="knowledge-base",
    page_content_field="body",
    external_id_key="source_id",
)

writer.add_documents([
    Document(page_content="…", metadata={"title": "Hybrid search",
                                         "source_id": "docs/hybrid-search"}),
])

Reusing a value raises ExternalIdConflict. A document without that metadata key is written without an external id — a collection may legitimately hold a mix. The value must be a str or int; anything else raises TypeError naming the document index, rather than silently turning an object into a key you could never reproduce.

update_document ignores external_id_key: update_resource addresses a resource by its internal key and takes no external one.

Controlling what gets written

Parameter Default Description
page_content_field — data field that receives page_content
document_mapper None Custom (document) -> dict for full control; mutually exclusive with page_content_field
metadata_fields None Whitelist of metadata keys to write
exclude_metadata_fields None Blacklist of metadata keys to skip
include_sys_metadata False Write the read path's _sys-derived keys (key, folder, created_at, updated_at)
external_id_key None Metadata key holding an external deduplication id

Exactly one of page_content_field / document_mapper must be set, and metadata_fields / exclude_metadata_fields are mutually exclusive.

A custom mapper takes over completely — every other mapping option is ignored:

writer = FoxNoseWriter(
    client=client,
    collection_path="articles",
    document_mapper=lambda d: {
        "body": d.page_content,
        "title": d.metadata.get("title", "Untitled"),
        "word_count": len(d.page_content.split()),
    },
)

Round-tripping

FoxNoseLoader and FoxNoseRetriever include _sys metadata by default, so a loaded document carries key, folder, created_at and updated_at. None of those are schema fields. The writer strips them automatically, so a read-edit-write cycle just works:

from langchain_foxnose import FoxNoseLoader, FoxNoseWriter

loader = FoxNoseLoader(
    client=client, collection_path="articles", page_content_field="body"
)
writer = FoxNoseWriter(
    client=client, collection_path="articles", page_content_field="body"
)

for doc in loader.load():
    doc.page_content = doc.page_content.strip()
    writer.update_document(doc.metadata["key"], doc)

Set include_sys_metadata=True on the writer only if your schema really does have fields with those names.

Errors

Every underlying error from add_documents / aadd_documents is wrapped in FoxNoseBatchWriteError. Branch on exc.cause — a second except clause after it is dead code:

from foxnose_sdk.errors import ContentValidationFailed, ExternalIdConflict
from langchain_foxnose import FoxNoseBatchWriteError

try:
    keys = writer.add_documents(documents)
except FoxNoseBatchWriteError as exc:
    print(f"Written, not rolled back: {exc.written_keys}")
    print(f"Unknown outcome:          document {exc.failed_index}")
    print(f"Not attempted:            {exc.pending_indexes}")

    cause = exc.cause
    if isinstance(cause, ExternalIdConflict):
        print("  that external id already exists")
    elif isinstance(cause, ContentValidationFailed):
        for problem in cause.errors:
            print(f"  {problem['json_path']}: {problem['message']}")
    raise

Needs foxnose-sdk 0.8.1

A Flux write reports a schema violation as data_validation_error, which earlier versions did not map onto ContentValidationFailed — it arrived as a plain FoxnoseAPIError, so the branch above never fired. Both codes raise the typed exception from 0.8.1 on, which is why that is the floor.

The three ranges mean exactly this:

Attribute Guarantee
written_keys Documents 0 … failed_index-1. Written and not rolled back — Flux has no delete endpoint, so they stay.
failed_index The document whose write raised. Its outcome is unknown, not "failed": a schema violation (422) or ExternalIdConflict (409) wrote nothing, but an UpstreamError (502) or a transport timeout may have written it.
pending_indexes Documents after the failure. Guaranteed not attempted — this is what the sequential, stop-at-first-failure design buys you.

Never blindly retry a failed write

For an UpstreamError or a timeout the write may already have landed. Re-read the resource with a GET to establish the real state before retrying, exactly as the SDK advises.

A local mapping error — a non-scalar external id, a metadata key colliding with page_content_field, a raising document_mapper — is raised as a plain TypeError / ValueError before any request is sent, so nothing is written. FoxNoseBatchWriteError is reserved for writes that were actually attempted.

Typed SDK errors you can meet directly from update_document (which writes one resource and therefore does not wrap):

Exception HTTP Meaning
CollectionNotWritable 403 The collection's connection does not accept writes, or the key lacks write access
ExternalIdConflict 409 The supplied external id already identifies a resource
ContentValidationFailed 422 data failed the collection schema; see .errors / .errors_truncated. Raised for both content_validation_failed and a Flux write's data_validation_error.
UpstreamError 502 The write could not be confirmed — outcome unknown

Requirements

Writes need a Flux key with write access, and the collection must be exposed on the API with create / update in its allowed methods. An anonymous caller gets 401; a key without the grant gets a generic 403.

Flux has no delete endpoint

Documents written by mistake cannot be removed through this integration. Use the Management API or the FoxNose dashboard.

API Reference

langchain_foxnose.writers.FoxNoseWriter

Write LangChain Documents into a FoxNose collection via Flux.

Each document becomes one FoxNose resource, published immediately. This is the write counterpart to :class:~langchain_foxnose.FoxNoseRetriever and :class:~langchain_foxnose.FoxNoseLoader.

Example

.. code-block:: python

from foxnose_sdk.flux import FluxClient
from foxnose_sdk.auth import SimpleKeyAuth
from langchain_core.documents import Document
from langchain_foxnose import FoxNoseWriter

client = FluxClient(
    base_url="https://<env_key>.fxns.io",
    api_prefix="my_api",
    auth=SimpleKeyAuth("pk", "sk"),
)
writer = FoxNoseWriter(
    client=client,
    collection_path="knowledge-base",
    page_content_field="body",
)
keys = writer.add_documents(
    [Document(page_content="Hello", metadata={"title": "Hi"})]
)

Parameters:

Name Type Description Default
client Any | None

Synchronous :class:~foxnose_sdk.flux.FluxClient instance.

None
async_client Any | None

Asynchronous :class:~foxnose_sdk.flux.AsyncFluxClient instance.

None
collection_path str

Collection path in FoxNose (e.g. "knowledge-base").

required
page_content_field str | None

data field that receives page_content.

None
document_mapper Callable[[Document], dict[str, Any]] | None

Custom callable (document) -> dict for full control over the written data. Mutually exclusive with page_content_field.

None
metadata_fields list[str] | None

Whitelist of metadata keys to write.

None
exclude_metadata_fields list[str] | None

Blacklist of metadata keys to skip.

None
include_sys_metadata bool

Whether to write the read path's _sys-derived metadata keys (key, folder, created_at, updated_at). Defaults to False — they are not schema fields.

False
external_id_key str | None

Metadata key holding an external deduplication id. Its value is sent as the resource key. The value must be a str or int; anything else raises TypeError. A document without the key is written without one. Reusing a value raises :class:~foxnose_sdk.errors.ExternalIdConflict. The key is kept out of data when page_content_field builds the mapping. With a document_mapper the mapper decides: whatever it returns is written as-is, so a mapper that copies all metadata will also write the identifier into data.

None
Note

Writes require a Flux key with write access. A collection whose connection does not accept writes raises :class:~foxnose_sdk.errors.CollectionNotWritable.

Data that fails the collection schema raises :class:~foxnose_sdk.errors.ContentValidationFailed, whose errors list locates each offending field. This needs foxnose-sdk 0.8.1: before that, a Flux write's data_validation_error was unmapped and arrived as a plain :class:~foxnose_sdk.errors.FoxnoseAPIError.

Note

Batches are written strictly sequentially and stop at the first failure — there is no concurrency option on purpose. Flux writes are non-idempotent, are never retried by the SDK, and cannot be deleted, so concurrent scheduling would leave the failure report unable to say which documents were attempted. See :class:FoxNoseBatchWriteError.

Methods:

from_client_params(*, base_url, api_prefix, auth, collection_path, async_mode=False, timeout=15.0, **kwargs) classmethod

Create a writer by constructing the Flux client internally.

Parameters:

Name Type Description Default
base_url str

FoxNose environment URL (e.g. "https://<env_key>.fxns.io").

required
api_prefix str

Flux API prefix.

required
auth Any

An :class:~foxnose_sdk.auth.AuthStrategy instance.

required
collection_path str

Collection path to write to.

required
async_mode bool

If True, create an AsyncFluxClient instead.

False
timeout float

HTTP timeout in seconds.

15.0
**kwargs Any

Additional arguments passed to :class:FoxNoseWriter.

{}

Returns:

Type Description
FoxNoseWriter

A configured :class:FoxNoseWriter instance.

add_documents(documents)

Create one FoxNose resource per document, sequentially.

Writes stop at the first failure; documents after it are not attempted. All documents are mapped and validated before the first request, so a mapping error writes nothing at all.

Parameters:

Name Type Description Default
documents Sequence[Document]

The documents to write.

required

Returns:

Type Description
list[str]

The created resource_key values, in input order.

Raises:

Type Description
ValueError

If no synchronous client is available, or a document cannot be mapped. Raised before any write is attempted.

TypeError

If a document's external id is not a str or int. Raised before any write is attempted.

FoxNoseBatchWriteError

If any write fails. Inspect exc.written_keys, exc.failed_index, exc.pending_indexes and exc.cause.

aadd_documents(documents) async

Create one FoxNose resource per document, sequentially.

Deliberately sequential with an early stop, exactly like :meth:add_documents: Flux writes are non-idempotent, are never retried by the SDK, and cannot be deleted, so overlapping them would make :class:FoxNoseBatchWriteError unable to say which documents were attempted. Chunk the input and call this method per chunk if you need concurrency and can accept that ambiguity.

Parameters:

Name Type Description Default
documents Sequence[Document]

The documents to write.

required

Returns:

Type Description
list[str]

The created resource_key values, in input order.

Raises:

Type Description
ValueError

If no async client is available, or a document cannot be mapped. Raised before any write is attempted.

TypeError

If a document's external id is not a str or int. Raised before any write is attempted.

FoxNoseBatchWriteError

If any write fails. Inspect exc.written_keys, exc.failed_index, exc.pending_indexes and exc.cause.

update_document(resource_key, document)

Replace a resource's document and publish a new revision.

This is a full-document replace, not a partial merge: fields absent from the mapped data are removed from the stored resource.

Parameters:

Name Type Description Default
resource_key str

Internal FoxNose resource key (as returned by :meth:add_documents or found in Document.metadata["key"]).

required
document Document

The replacement document.

required

Returns:

Type Description
str

The new revision_key.

Raises:

Type Description
ValueError

If no synchronous client is available.

aupdate_document(resource_key, document) async

Async variant of :meth:update_document.

Raises:

Type Description
ValueError

If no async client is available.

langchain_foxnose.writers.FoxNoseBatchWriteError

Bases: RuntimeError

Raised when a document batch fails part-way through.

Flux writes are non-idempotent, are never retried automatically, and cannot be rolled back or deleted, so a failed batch leaves earlier documents in place. Batches are written strictly sequentially and stop at the first failure, which is what makes the three index ranges below meaningful.

Attributes:

Name Type Description
written_keys

resource_key of documents 0 .. failed_index - 1, confirmed written and not rolled back.

failed_index

Index of the document whose write raised. Its outcome is unknown, not necessarily failed — a :class:~foxnose_sdk.errors.ContentValidationFailed or :class:~foxnose_sdk.errors.ExternalIdConflict wrote nothing, but an :class:~foxnose_sdk.errors.UpstreamError or a transport timeout may have written it. Re-read with a GET to find out; do not blindly retry.

pending_indexes

Indexes failed_index + 1 .. total - 1, guaranteed not attempted.

total

Number of documents in the batch.

Attributes

cause property

The underlying SDK error. Branch on type(exc.cause).

A second except clause after FoxNoseBatchWriteError never fires for a batch write — every underlying error is wrapped.