Skip to main content

ChatCompletion

Struct ChatCompletion 

Source
pub struct ChatCompletion<N, M, S = StreamOff>{
    pub key: String,
    pub url: String,
    /* private fields */
}
Expand description

Type-safe chat completion request structure.

This struct represents a chat completion request with compile-time guarantees for model compatibility and streaming capabilities.

§Type Parameters

  • N - The AI model type (must implement ModelName + Chat)
  • M - The message type (must form a valid bound with the model)
  • S - Stream state (StreamOn or StreamOff, defaults to StreamOff)

§Examples

let model = GLM4_5_flash {};
let messages = TextMessage::user("Hello, how are you?");
let request = ChatCompletion::new(model, messages, api_key);

Fields§

§key: String

API key for authentication with the Zhipu AI service.

§url: String

API endpoint URL for chat completions. Defaults to “https://open.bigmodel.cn/api/paas/v4/chat/completions” but can be customized using the with_url() method.

Implementations§

Source§

impl<N, M> ChatCompletion<N, M, StreamOff>

Source

pub fn new( model: N, messages: M, key: String, ) -> ChatCompletion<N, M, StreamOff>

Creates a new non-streaming chat completion request.

§Arguments
  • model - The AI model to use for completion
  • messages - The conversation messages
  • key - API key for authentication
§Returns

A new ChatCompletion instance configured for non-streaming requests.

Source

pub fn body_mut(&mut self) -> &mut ChatBody<N, M>

Gets mutable access to the request body for further customization.

This method allows modification of request parameters after initial creation.

Source

pub fn add_messages(self, messages: M) -> Self

Adds additional messages to the conversation.

This method provides a fluent interface for building conversation context.

§Arguments
  • messages - Additional messages to append to the conversation
§Returns

Self with the updated message collection, enabling method chaining.

Source

pub fn with_request_id(self, request_id: impl Into<String>) -> Self

Source

pub fn with_do_sample(self, do_sample: bool) -> Self

Source

pub fn with_temperature(self, temperature: f32) -> Self

Source

pub fn with_top_p(self, top_p: f32) -> Self

Source

pub fn with_max_tokens(self, max_tokens: u32) -> Self

Source

pub fn add_tool(self, tool: Tools) -> Self

Source

pub fn add_tools(self, tools: Vec<Tools>) -> Self

Source

pub fn with_user_id(self, user_id: impl Into<String>) -> Self

Source

pub fn with_stop(self, stop: String) -> Self

Source

pub fn with_url(self, url: impl Into<String>) -> Self

Sets a custom API endpoint URL for this chat completion request.

This method allows overriding the default API endpoint with a custom URL, enabling support for different deployment environments or proxy configurations.

§Arguments
  • url - The custom API endpoint URL
§Returns

Self with the updated URL, enabling method chaining.

§Examples
let request = ChatCompletion::new(model, messages, api_key)
    .with_url("https://custom-api.example.com/v1/chat/completions");
Source

pub fn with_coding_plan(self) -> Self

Sets the URL to the coding plan endpoint.

This method configures the chat completion request to use the coding-specific API endpoint “https://open.bigmodel.cn/api/coding/paas/v4/chat/completions”.

§Returns

Self with the coding plan URL, enabling method chaining.

§Examples
let request = ChatCompletion::new(model, messages, api_key)
    .with_coding_plan();
Source

pub fn with_thinking(self, thinking: ThinkingType) -> Self
where N: ThinkEnable,

Source

pub fn enable_stream(self) -> ChatCompletion<N, M, StreamOn>

Enables streaming for this chat completion request.

This method transitions the request to streaming mode, allowing real-time response processing through Server-Sent Events (SSE).

§Returns

A new ChatCompletion instance with streaming enabled (StreamOn).

Source

pub fn validate(&self) -> ZaiResult<()>

Validate request parameters for non-stream chat (StreamOff)

Source

pub async fn send(&self) -> ZaiResult<ChatCompletionResponse>
where N: Serialize, M: Serialize,

Source§

impl<N, M> ChatCompletion<N, M, StreamOn>

Source

pub fn with_tool_stream(self, tool_stream: bool) -> Self

Source

pub fn disable_stream(self) -> ChatCompletion<N, M, StreamOff>

Disables streaming for this chat completion request.

This method ensures the request will receive a complete response rather than streaming chunks.

§Returns

A new ChatCompletion instance with streaming disabled (StreamOff).

Trait Implementations§

Source§

impl<N, M, S> HttpClient for ChatCompletion<N, M, S>

Source§

fn api_url(&self) -> &Self::ApiUrl

Returns the API endpoint URL for chat completions.

Source§

type Body = ChatBody<N, M>

Source§

type ApiUrl = String

Source§

type ApiKey = String

Source§

fn api_key(&self) -> &Self::ApiKey

Source§

fn body(&self) -> &Self::Body

Source§

fn http_config(&self) -> Arc<HttpClientConfig>

Get HTTP client configuration for this request Read more
Source§

fn post(&self) -> impl Future<Output = ZaiResult<Response>> + Send

Sends a POST request to the API endpoint. Read more
Source§

fn get(&self) -> impl Future<Output = ZaiResult<Response>> + Send

Sends a GET request to the API endpoint. Read more
Source§

impl<N, M> SseStreamable for ChatCompletion<N, M, StreamOn>

Enables Server-Sent Events (SSE) streaming for streaming-enabled chat completions.

This implementation allows streaming chat completions to be processed incrementally as responses arrive from the API.

Source§

fn stream_sse_for_each<'a, F>( &'a mut self, on_data: F, ) -> impl Future<Output = ZaiResult<()>> + 'a
where F: FnMut(&[u8]) + 'a,

Source§

impl<N, M> StreamChatLikeExt for ChatCompletion<N, M, StreamOn>

Provides streaming extension methods for streaming-enabled chat completions.

This implementation enables the use of streaming-specific methods for processing chat responses in real-time.

Source§

fn stream_for_each<'a, F, Fut>( &'a mut self, on_chunk: F, ) -> impl Future<Output = ZaiResult<()>> + 'a
where F: FnMut(ChatStreamResponse) -> Fut + 'a, Fut: Future<Output = ZaiResult<()>> + 'a,

Processes streaming responses using an async callback function. Read more
Source§

fn to_stream<'a>( &'a mut self, ) -> impl Future<Output = ZaiResult<Pin<Box<dyn Stream<Item = ZaiResult<ChatStreamResponse>> + Send + 'static>>>> + 'a

Converts the streaming response into a composable Stream. Read more

Auto Trait Implementations§

§

impl<N, M, S> Freeze for ChatCompletion<N, M, S>
where N: Freeze,

§

impl<N, M, S> RefUnwindSafe for ChatCompletion<N, M, S>

§

impl<N, M, S> Send for ChatCompletion<N, M, S>
where N: Send, S: Send, M: Send,

§

impl<N, M, S> Sync for ChatCompletion<N, M, S>
where N: Sync, S: Sync, M: Sync,

§

impl<N, M, S> Unpin for ChatCompletion<N, M, S>
where N: Unpin, S: Unpin, M: Unpin,

§

impl<N, M, S> UnsafeUnpin for ChatCompletion<N, M, S>
where N: UnsafeUnpin,

§

impl<N, M, S> UnwindSafe for ChatCompletion<N, M, S>
where N: UnwindSafe, S: UnwindSafe, M: UnwindSafe,

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> 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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. 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