Skip to main content

ModelClient

Struct ModelClient 

Source
pub struct ModelClient { /* private fields */ }
Expand description

A client for interacting with the Ollama API.

Implementations§

Source§

impl ModelClient

Source

pub async fn chat(&self, request: ChatRequest) -> Result<ChatResponse>

Generate a chat completion.

Source

pub async fn chat_stream( &self, request: ChatRequest, ) -> Result<impl Stream<Item = Result<ChatResponse>> + '_>

Generate a streaming chat completion.

Source§

impl ModelClient

Source

pub fn builder() -> ModelClientBuilder

Create a new builder for a ModelClient.

Source

pub fn base_url(&self) -> &Url

Get the configured base URL.

Source

pub fn is_authenticated(&self) -> bool

Check if authentication is configured.

Source

pub async fn handle_response<T>( &self, response: Response, model: Option<&str>, ) -> Result<T>
where for<'a> T: Deserialize<'a>,

Helper method to handle responses consistently.

Source

pub async fn handle_void_response(&self, response: Response) -> Result<()>

Helper method to handle responses that return nothing (Result<()>).

Source

pub async fn get_version(&self) -> Result<VersionResponse>

Get the version of the Ollama API.

Source§

impl ModelClient

Source

pub async fn embed(&self, request: EmbedRequest) -> Result<EmbedResponse>

Generate embeddings from text.

Source

pub async fn embeddings( &self, request: EmbeddingsRequest, ) -> Result<EmbeddingsResponse>

Generate legacy embeddings from text.

Source§

impl ModelClient

Source

pub async fn generate( &self, request: GenerateRequest, ) -> Result<GenerateResponse>

Generate text from a prompt.

Source

pub async fn generate_stream( &self, request: GenerateRequest, ) -> Result<impl Stream<Item = Result<GenerateResponse>> + '_>

Generate text from a prompt with streaming.

Source§

impl ModelClient

Source

pub async fn list_models(&self) -> Result<Vec<ModelInfo>>

List local models.

Source

pub async fn show_model( &self, request: ShowModelRequest, ) -> Result<ShowModelResponse>

Show information about a model.

Source

pub async fn copy_model(&self, request: CopyModelRequest) -> Result<()>

Copy a model.

Source

pub async fn delete_model(&self, request: DeleteModelRequest) -> Result<()>

Delete a model.

Source

pub async fn pull_model( &self, request: PullModelRequest, ) -> Result<impl Stream<Item = Result<StatusResponse>> + '_>

Pull a model.

Source

pub async fn push_model( &self, request: PushModelRequest, ) -> Result<impl Stream<Item = Result<StatusResponse>> + '_>

Push a model.

Source

pub async fn create_model( &self, request: CreateModelRequest, ) -> Result<impl Stream<Item = Result<StatusResponse>> + '_>

Create a model.

Source§

impl ModelClient

Source

pub async fn chat_completions( &self, request: ChatCompletionsRequest, ) -> Result<ChatCompletionsResponse>

Create chat completions using OpenAI-compatible API

This endpoint is compatible with OpenAI client libraries. Use base URL http://localhost:11434/v1/ with any API key.

§Example
use oai_sdk::{ModelClient, ChatCompletionsRequest, ChatMessage};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ModelClient::builder()
        .base_url("http://localhost:11434")
        .build()?;

    let request = ChatCompletionsRequest {
        model: "llama3.1:8b".to_string(),
        messages: vec![ChatMessage::user("Why is the sky blue?")],
        stream: Some(false),
        ..Default::default()
    };

    let response = client.chat_completions(request).await?;
    println!("{}", response.choices[0].message.content);

    Ok(())
}
Source

pub async fn openai_embeddings( &self, request: OpenAIEmbeddingsRequest, ) -> Result<OpenAIEmbeddingsResponse>

Generate embeddings using OpenAI-compatible API

This endpoint is compatible with OpenAI client libraries. Use base URL http://localhost:11434/v1/ with any API key.

§Example
use oai_sdk::{ModelClient, OpenAIEmbeddingsRequest, OpenAIEmbeddingsInput};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ModelClient::builder()
        .base_url("http://localhost:11434")
        .build()?;

    let request = OpenAIEmbeddingsRequest {
        model: "llama3.1:8b".to_string(),
        input: OpenAIEmbeddingsInput::Single("Why is the sky blue?".to_string()),
        encoding_format: Some("float".to_string()),
        ..Default::default()
    };

    let response = client.openai_embeddings(request).await?;
    println!("Embeddings: {:?}", response.data[0].embedding);

    Ok(())
}
Source

pub async fn responses( &self, request: ResponsesRequest, ) -> Result<ResponsesResponse>

Generate responses using OpenAI-compatible API

This endpoint is compatible with OpenAI client libraries. Use base URL http://localhost:11434/v1/ with any API key.

§Example
use oai_sdk::{ModelClient, ResponsesRequest};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = ModelClient::builder()
        .base_url("http://localhost:11434")
        .build()?;

    let request = ResponsesRequest {
        model: "llama3.1:8b".to_string(),
        input: Some("Why is the sky blue?".to_string()),
        stream: Some(false),
        ..Default::default()
    };

    let response = client.responses(request).await?;
    println!("{}", response.output);

    Ok(())
}

Trait Implementations§

Source§

impl Clone for ModelClient

Source§

fn clone(&self) -> ModelClient

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ModelClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more