Designing a Provider-Agnostic RAG Integration in Rust with Axum and RAGFlow

By Ross Wilson

about 1 month ago

One of the latest features we’ve been developing at Crown Shy is an integrated Retrieval-Augmented Generation (RAG) system on the Comhairle platform, which powers tailored chat bots and agents with trusted sources. Rather than relying purely on model knowledge, which has the potential for LLMs to hallucinate answers to users, these bots can reference curated knowledge bases, giving users more reliable responses.

Comhairle integrates with several third-party projects that align with its goals, prioritising open source technologies, and is designed to avoid being tightly coupled to specific tools or providers (vendor lock-in). If an open source project we depend on stops being maintained, or for other reasons we decide to move away from it, we need the ability to swap out providers smoothly without losing functionality. That led us to design a trait-based service (bot_service) layer in our Rust + Axum backend, such that the required behaviour is described in the application state without worrying about implementation details.

Choosing a provider

When it came to choosing a RAG provider, we needed something that we could experiment with and iterate over quickly, was open source, supported self-hosting, and exposed an HTTP API.

We chose RAGFlow as our initial provider, an open source RAG engine that provides both a ready to use GUI and an HTTP API. The GUI allowed us to get up and running quickly and experiment with and fine tune features without having to write any code first.

On the deployment side, there are community-provided helm charts available that we were able to leverage to self host our own RAGFlow instance on our kubernetes cluster, fitting in with the rest of our deployment architecture.

The HTTP API was of particular importance to us. We didn’t want our users to have to interact with an external interface, but rather build the functionality we needed into the Comhairle UI. Having an HTTP API meant we could treat RAGFlow as an engine behind the scenes rather than a user-facing tool.

Client

The first step was building an HTTP client for the RAGFlow API in Rust.

Comhairle is structured as a monorepo, with separate adaptor crates for integrating with external service providers. That separation keeps our core API layer from depending directly on third-party implementations and supports our goal of decoupling the platform from specific vendors. The RAGFlow integration followed the same pattern and was implemented as a new adaptor crate.

We implemented methods for most of the exposed RAGFlow endpoints, including management of: datasets (knowledge bases) documents chats and chat sessions agents and agent sessions

Bot service trait

With the client build, the next step was to integrate it into our Axum API without coupling the rest of the application to RAGFlow directly.

To do that, we created a new async trait, ComhairleBotService, which defined the behaviour our application expects from a “bot provider” (i.e. managing sessions / uploading files to knowledge bases) without specifying how these operations are implemented.

The trait is then stored in application state as a trait object:

Using a trait object is what allows us to avoid vendor lock-in by leaving us open to creating other implementations of the trait for different providers in the future.

Challenges: Streamed responses

One of the friction points we encountered with this integration was streamed responses.

Like many LLMs, endpoints for conversing with a chat or agent can return server-sent events (SSE) so that responses can be streamed incrementally. Ideal from a UX perspective, and definitely something that users familiar with LLMs will expect, but it slightly complicated our tooling.

We use the aide crate to generate OpenAPI documentation from our Axum handlers. That OpenAPI spec is then used to generate a typed API client for our Svelte frontend. In most cases this works well and keeps the backend and frontend in sync with very little manual effort.

Streaming endpoints, however, don’t fit neatly into that pipeline.

Our initial implementation streamed the responses directly by returning axum::body::Body. That works perfectly at runtime but Body does not implement aide::OperationOutput, which aide requires on a response in order to generate OpenAPI documentation for a handler.

The workaround we ended up using was to create a small wrapper struct which could derive aide::OperationIo so that documentation could be generated, as well as implement axum::response::IntoResponse and forward the inner streamed body from the request handler.

Perhaps not the most elegant solution, but it at least keeps streaming intact while preserving documentation generation.

Another challenge related to the streamed endpoints concerned generating client methods for those endpoints from the OpenAPI spec created by aide. On success, the endpoints return server-sent event chunks (prefixed with data: ). On error, they return standard JSON error responses. Meaning the frontend cannot simply deserialize the response body as JSON. Instead it has to:

Create a reader on the response body Decode incoming byte chunks to UTF-8 Parse each chunk Determine whether it represents: A JSON error object An SSE data: message

This kind of logic doesn’t map cleanly to an OpenAPI schema, which assumes a well-defined response type. As a result, our generated client couldn’t meaningfully represent this endpoint.

In the end, we opted to exclude these endpoints from client generation by omitting certain transform operation calls and instead documented them explicitly with instructions to consumers to use raw requests and process the responses incrementally.

Challenges: Background worker scheduling

Another issue we ran into was the need for background job processing.

We had always expected to introduce some form of background worker system on the platform eventually, but the bot service required us to expedite it. One part of how the bot service sat in our application flow didn’t fit into a synchronous request-response model.

The first feature we built with the bot service was a tutor bot attached to a conversation. Each conversation is associated with its own knowledge base, containing documents relevant to the conversation topic, and a chat bot constrained to those documents.

When a conversation is created, we also create a corresponding RAGFlow knowledge base and chat. In an ideal scenario, the chat would point to the knowledge base when it is created. However, RAGflow does not allow a chat to be created against a knowledge base that contains no parsed documents. This makes sense. A chat constrained to an empty knowledge base would have no resources to draw on.

The problem is that document parsing can take a non-trivial amount of time, especially for large or complex files. Too long to expect a user to wait on a response from a single “create conversation” request. Therefore, we decided to split the workflow. When a conversation is first created, we create its associated knowledge base and chat, but we initialise the chat against a default knowledge base containing general documentation of the Comhairle platform itself. This allows the chat to be available immediately, even if it is not yet specialised to the conversation.

Then, when a user uploads a document to the conversation’s knowledge base, we schedule a background job. That job periodically polls RAGFlow for the document’s parse status. Once parsing is complete, the job checks whether the conversation’s chat bot is already pointing to its knowledge base. If it isn’t, the worker updates the chat so it references the conversation’s knowledge base.

From the user’s perspective, this happens transparently. The conversation creator can start testing out interactions with the chat bot right away (albeit with limited responses) and as soon as their documents are ready, the bot begins sourcing its answers from those.

This approach allowed us to keep the API responsive while working within RAGFlow’s constraints, and at the same time gave us the foundation for handling long running tasks in the future.

Building a provider-agnostic RAG integration in Comhairle taught us a lot about how we want to shape our architecture as well as about working with the quirks of external systems. Using the trait-based service layer let us decouple the platform from any single provider, keeping the door open for swapping out implementations whilst also laying the groundwork for how we can integrate other services in the future without vendor lock-in.

Along the way, we ran into challenges we expect to encounter again in the future so the solutions we implemented can be built upon when such cases arise.

The RAG integration now provides users with responses from trusted sources whilst keeping our system flexible.