async_openai_alt/
threads.rs

1use crate::{
2    config::Config,
3    error::OpenAIError,
4    types::{
5        AssistantEventStream, AssistantStreamEvent, CreateThreadAndRunRequest, CreateThreadRequest,
6        DeleteThreadResponse, ModifyThreadRequest, RunObject, ThreadObject,
7    },
8    Client, Messages, Runs,
9};
10
11/// Create threads that assistants can interact with.
12///
13/// Related guide: [Assistants](https://platform.openai.com/docs/assistants/overview)
14pub struct Threads<'c, C: Config> {
15    client: &'c Client<C>,
16}
17
18impl<'c, C: Config> Threads<'c, C> {
19    pub fn new(client: &'c Client<C>) -> Self {
20        Self { client }
21    }
22
23    /// Call [Messages] group API to manage message in [thread_id] thread.
24    pub fn messages(&self, thread_id: &str) -> Messages<C> {
25        Messages::new(self.client, thread_id)
26    }
27
28    /// Call [Runs] group API to manage runs in [thread_id] thread.
29    pub fn runs(&self, thread_id: &str) -> Runs<C> {
30        Runs::new(self.client, thread_id)
31    }
32
33    /// Create a thread and run it in one request.
34    pub async fn create_and_run(
35        &self,
36        request: CreateThreadAndRunRequest,
37    ) -> Result<RunObject, OpenAIError> {
38        self.client.post("/threads/runs", request).await
39    }
40
41    /// Create a thread and run it in one request (streaming).
42    pub async fn create_and_run_stream(
43        &self,
44        mut request: CreateThreadAndRunRequest,
45    ) -> Result<AssistantEventStream, OpenAIError> {
46        if request.stream.is_some() && !request.stream.unwrap() {
47            return Err(OpenAIError::InvalidArgument(
48                "When stream is false, use Threads::create_and_run".into(),
49            ));
50        }
51
52        request.stream = Some(true);
53
54        Ok(self
55            .client
56            .post_stream_mapped_raw_events("/threads/runs", request, AssistantStreamEvent::try_from)
57            .await)
58    }
59
60    /// Create a thread.
61    pub async fn create(&self, request: CreateThreadRequest) -> Result<ThreadObject, OpenAIError> {
62        self.client.post("/threads", request).await
63    }
64
65    /// Retrieves a thread.
66    pub async fn retrieve(&self, thread_id: &str) -> Result<ThreadObject, OpenAIError> {
67        self.client.get(&format!("/threads/{thread_id}")).await
68    }
69
70    /// Modifies a thread.
71    pub async fn update(
72        &self,
73        thread_id: &str,
74        request: ModifyThreadRequest,
75    ) -> Result<ThreadObject, OpenAIError> {
76        self.client
77            .post(&format!("/threads/{thread_id}"), request)
78            .await
79    }
80
81    /// Delete a thread.
82    pub async fn delete(&self, thread_id: &str) -> Result<DeleteThreadResponse, OpenAIError> {
83        self.client.delete(&format!("/threads/{thread_id}")).await
84    }
85}