async_openai_wasm/
chat.rs

1use crate::{
2    config::Config,
3    error::OpenAIError,
4    types::{
5        ChatCompletionResponseStream, CreateChatCompletionRequest, CreateChatCompletionResponse,
6    },
7    Client,
8};
9
10/// Given a list of messages comprising a conversation, the model will return a response.
11///
12/// Related guide: [Chat completions](https://platform.openai.com//docs/guides/text-generation)
13pub struct Chat<'c, C: Config> {
14    client: &'c Client<C>,
15}
16
17impl<'c, C: Config> Chat<'c, C> {
18    pub fn new(client: &'c Client<C>) -> Self {
19        Self { client }
20    }
21
22    /// Creates a model response for the given chat conversation. Learn more in
23    /// the
24    ///
25    /// [text generation](https://platform.openai.com/docs/guides/text-generation),
26    /// [vision](https://platform.openai.com/docs/guides/vision),
27    ///
28    /// and [audio](https://platform.openai.com/docs/guides/audio) guides.
29    ///
30    ///
31    /// Parameter support can differ depending on the model used to generate the
32    /// response, particularly for newer reasoning models. Parameters that are
33    /// only supported for reasoning models are noted below. For the current state
34    /// of unsupported parameters in reasoning models,
35    ///
36    /// [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).
37    pub async fn create(
38        &self,
39        request: CreateChatCompletionRequest,
40    ) -> Result<CreateChatCompletionResponse, OpenAIError> {
41        if request.stream.is_some() && request.stream.unwrap() {
42            return Err(OpenAIError::InvalidArgument(
43                "When stream is true, use Chat::create_stream".into(),
44            ));
45        }
46        self.client.post("/chat/completions", request).await
47    }
48
49    /// Creates a completion for the chat message
50    ///
51    /// partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message.
52    ///
53    /// [ChatCompletionResponseStream] is a parsed SSE stream until a \[DONE\] is received from server.
54    pub async fn create_stream(
55        &self,
56        mut request: CreateChatCompletionRequest,
57    ) -> Result<ChatCompletionResponseStream, OpenAIError> {
58        if request.stream.is_some() && !request.stream.unwrap() {
59            return Err(OpenAIError::InvalidArgument(
60                "When stream is false, use Chat::create".into(),
61            ));
62        }
63
64        request.stream = Some(true);
65
66        Ok(self.client.post_stream("/chat/completions", request).await)
67    }
68}