Struct ChatCompletion

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

OpenAI Chat Completions API client

This structure manages interactions with the OpenAI Chat Completions API. It handles API key management, request parameter configuration, and API calls.

§Example

use openai_tools::chat::request::ChatCompletion;
use openai_tools::common::message::Message;
use openai_tools::common::role::Role;

let mut chat = ChatCompletion::new();
let messages = vec![Message::from_string(Role::User, "Hello!")];

let response = chat
    .model_id("gpt-4o-mini")
    .messages(messages)
    .temperature(1.0)
    .chat()
    .await?;

Implementations§

Source§

impl ChatCompletion

Source

pub fn new() -> Self

Creates a new ChatCompletion instance

Loads the API key from the OPENAI_API_KEY environment variable. If a .env file exists, it will also be loaded.

§Panics

Panics if the OPENAI_API_KEY environment variable is not set.

§Returns

A new ChatCompletion instance

Source

pub fn model_id<T: AsRef<str>>(&mut self, model_id: T) -> &mut Self

Sets the model ID to use

§Arguments
  • model_id - OpenAI model ID (e.g., gpt-4o-mini, gpt-4o)
§Returns

A mutable reference to self for method chaining

Source

pub fn messages(&mut self, messages: Vec<Message>) -> &mut Self

Sets the chat message history

§Arguments
  • messages - Vector of chat messages representing the conversation history
§Returns

A mutable reference to self for method chaining

Source

pub fn store(&mut self, store: bool) -> &mut Self

Sets whether to store the request and response at OpenAI

§Arguments
  • store - true to store, false to not store
§Returns

A mutable reference to self for method chaining

Source

pub fn frequency_penalty(&mut self, frequency_penalty: f32) -> &mut Self

Sets the frequency penalty

A parameter that penalizes based on word frequency to reduce repetition. Positive values decrease repetition, negative values increase it.

§Arguments
  • frequency_penalty - Frequency penalty value (range: -2.0 to 2.0)
§Returns

A mutable reference to self for method chaining

Source

pub fn logit_bias<T: AsRef<str>>( &mut self, logit_bias: HashMap<T, i32>, ) -> &mut Self

Sets logit bias to adjust the probability of specific tokens

§Arguments
  • logit_bias - A map of token IDs to adjustment values
§Returns

A mutable reference to self for method chaining

Source

pub fn logprobs(&mut self, logprobs: bool) -> &mut Self

Sets whether to include probability information for each token

§Arguments
  • logprobs - true to include probability information
§Returns

A mutable reference to self for method chaining

Source

pub fn top_logprobs(&mut self, top_logprobs: u8) -> &mut Self

Sets the number of top probabilities to return for each token

§Arguments
  • top_logprobs - Number of top probabilities (range: 0-20)
§Returns

A mutable reference to self for method chaining

Source

pub fn max_completion_tokens(&mut self, max_completion_tokens: u64) -> &mut Self

Sets the maximum number of tokens to generate

§Arguments
  • max_completion_tokens - Maximum number of tokens
§Returns

A mutable reference to self for method chaining

Source

pub fn n(&mut self, n: u32) -> &mut Self

Sets the number of responses to generate

§Arguments
  • n - Number of responses to generate
§Returns

A mutable reference to self for method chaining

Source

pub fn modalities<T: AsRef<str>>(&mut self, modalities: Vec<T>) -> &mut Self

Sets the available modalities for the response

§Arguments
  • modalities - List of modalities (e.g., ["text", "audio"])
§Returns

A mutable reference to self for method chaining

Source

pub fn presence_penalty(&mut self, presence_penalty: f32) -> &mut Self

Sets the presence penalty

A parameter that controls the tendency to include new content in the document. Positive values encourage talking about new topics, negative values encourage staying on existing topics.

§Arguments
  • presence_penalty - Presence penalty value (range: -2.0 to 2.0)
§Returns

A mutable reference to self for method chaining

Source

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

Sets the temperature parameter to control response randomness

Higher values (e.g., 1.0) produce more creative and diverse outputs, while lower values (e.g., 0.2) produce more deterministic and consistent outputs.

§Arguments
  • temperature - Temperature parameter (range: 0.0 to 2.0)
§Returns

A mutable reference to self for method chaining

Source

pub fn json_schema(&mut self, json_schema: Schema) -> &mut Self

Sets structured output using JSON schema

Enables receiving responses in a structured JSON format according to the specified JSON schema.

§Arguments
  • json_schema - JSON schema defining the response structure
§Returns

A mutable reference to self for method chaining

Source

pub fn tools(&mut self, tools: Vec<Tool>) -> &mut Self

Sets the tools that can be called by the model

Enables function calling by providing a list of tools that the model can choose to call. When tools are provided, the model may generate tool calls instead of or in addition to regular text responses.

§Arguments
  • tools - Vector of tools available for the model to use
§Returns

A mutable reference to self for method chaining

Source

pub fn get_message_history(&self) -> Vec<Message>

Gets the current message history

§Returns

A vector containing the message history

Source

pub async fn chat(&mut self) -> Result<Response>

Sends the chat completion request to OpenAI API

This method validates the request parameters, constructs the HTTP request, and sends it to the OpenAI Chat Completions endpoint.

§Returns

A Result containing the API response on success, or an error on failure.

§Errors

Returns an error if:

  • API key is not set
  • Model ID is not set
  • Messages are empty
  • Network request fails
  • Response parsing fails
§Example
use openai_tools::chat::request::ChatCompletion;
use openai_tools::common::message::Message;
use openai_tools::common::role::Role;

let mut chat = ChatCompletion::new();
let messages = vec![Message::from_string(Role::User, "Hello!")];

let response = chat
    .model_id("gpt-4o-mini")
    .messages(messages)
    .temperature(1.0)
    .chat()
    .await?;
     
println!("{}", response.choices[0].message.content.as_ref().unwrap().text.as_ref().unwrap());

Trait Implementations§

Source§

impl Clone for ChatCompletion

Source§

fn clone(&self) -> ChatCompletion

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ChatCompletion

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Default for ChatCompletion

Source§

fn default() -> ChatCompletion

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ChatCompletion

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for ChatCompletion

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. 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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
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<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
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
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,