Skip to content

refactor: use Typestate in TranscriptionRequestBuilder and VectorSearchRequestBuilder to avoid runtime checks #1610

@isSerge

Description

@isSerge
  • I have looked for existing issues (including closed) about this

Feature Request

Problem with TranscriptionRequestBuilder:

If someone forgets to provide data, calling .build() will trigger panic.

Location: src/transcription.rs:

pub fn build(self) -> TranscriptionRequest {
    if self.data.is_empty() {
        panic!("Data cannot be empty!")
    }
    // ...
}

Problem with VectorSearchRequestBuilder:

Location: src/vector_store/request.rs:

Builder returns a runtime Result if query is missing forcing user to handle misconfiguration error.

pub fn build(self) -> Result<VectorSearchRequest<F>, VectorStoreError> {
    let Some(query) = self.query else {
        return Err(VectorStoreError::BuilderError("`query` is a required...".into()));
    };
    // ...
}

Both of these problems can be mitigated at compile-time similar to AgentBuilder and ClientBuilder by using Typestate pattern.

Motivation

  1. Eliminate runtime panic in TranscriptionRequestBuilder
  2. Improved DX when building vector search requests

Proposal

  • Define universal state markers: Missing (default) and Provided for all builders.
  • Initialize with Missing state
  • Implement state transitions to Provided within .data() and .load_file() and similar methods
  • Implement terminal methods (.build() and .send()) only for Provided state

Alternatives

This might require introduction of additional generics, but is still arguably better and follows existing approach in other builders

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions