threads.rs 3.82 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Based on https://github.com/64bit/async-openai/ by Himanshu Neema
// Original Copyright (c) 2022 Himanshu Neema
// Licensed under MIT License (see ATTRIBUTIONS-Rust.md)
//
// Modifications Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES.
// Licensed under Apache 2.0

use crate::{
12
    Client, Messages, Runs,
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    config::Config,
    error::OpenAIError,
    types::{
        AssistantEventStream, CreateThreadAndRunRequest, CreateThreadRequest, DeleteThreadResponse,
        ModifyThreadRequest, RunObject, ThreadObject,
    },
};

/// Create threads that assistants can interact with.
///
/// Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview)
pub struct Threads<'c, C: Config> {
    client: &'c Client<C>,
}

impl<'c, C: Config> Threads<'c, C> {
    pub fn new(client: &'c Client<C>) -> Self {
        Self { client }
    }

    /// Call [Messages] group API to manage message in [thread_id] thread.
    pub fn messages(&self, thread_id: &str) -> Messages<C> {
        Messages::new(self.client, thread_id)
    }

    /// Call [Runs] group API to manage runs in [thread_id] thread.
    pub fn runs(&self, thread_id: &str) -> Runs<C> {
        Runs::new(self.client, thread_id)
    }

    /// Create a thread and run it in one request.
    #[crate::byot(T0 = serde::Serialize, R = serde::de::DeserializeOwned)]
    pub async fn create_and_run(
        &self,
        request: CreateThreadAndRunRequest,
    ) -> Result<RunObject, OpenAIError> {
        self.client.post("/threads/runs", request).await
    }

    /// Create a thread and run it in one request (streaming).
    ///
    /// byot: You must ensure "stream: true" in serialized `request`
    #[crate::byot(
        T0 = serde::Serialize,
        R = serde::de::DeserializeOwned,
        stream = "true",
        where_clause = "R: std::marker::Send + 'static + TryFrom<eventsource_stream::Event, Error = OpenAIError>"
    )]
    #[allow(unused_mut)]
    pub async fn create_and_run_stream(
        &self,
        mut request: CreateThreadAndRunRequest,
    ) -> Result<AssistantEventStream, OpenAIError> {
        #[cfg(not(feature = "byot"))]
        {
            if request.stream.is_some() && !request.stream.unwrap() {
                return Err(OpenAIError::InvalidArgument(
                    "When stream is false, use Threads::create_and_run".into(),
                ));
            }

            request.stream = Some(true);
        }
        Ok(self
            .client
            .post_stream_mapped_raw_events("/threads/runs", request, TryFrom::try_from)
            .await)
    }

    /// Create a thread.
    #[crate::byot(T0 = serde::Serialize, R = serde::de::DeserializeOwned)]
    pub async fn create(&self, request: CreateThreadRequest) -> Result<ThreadObject, OpenAIError> {
        self.client.post("/threads", request).await
    }

    /// Retrieves a thread.
    #[crate::byot(T0 = std::fmt::Display, R = serde::de::DeserializeOwned)]
    pub async fn retrieve(&self, thread_id: &str) -> Result<ThreadObject, OpenAIError> {
        self.client.get(&format!("/threads/{thread_id}")).await
    }

    /// Modifies a thread.
    #[crate::byot(T0 = std::fmt::Display, T1 = serde::Serialize, R = serde::de::DeserializeOwned)]
    pub async fn update(
        &self,
        thread_id: &str,
        request: ModifyThreadRequest,
    ) -> Result<ThreadObject, OpenAIError> {
        self.client
            .post(&format!("/threads/{thread_id}"), request)
            .await
    }

    /// Delete a thread.
    #[crate::byot(T0 = std::fmt::Display, R = serde::de::DeserializeOwned)]
    pub async fn delete(&self, thread_id: &str) -> Result<DeleteThreadResponse, OpenAIError> {
        self.client.delete(&format!("/threads/{thread_id}")).await
    }
}