swiftide_core/chat_completion/
errors.rs

1use thiserror::Error;
2
3use crate::CommandError;
4
5use super::ChatCompletionStream;
6
7#[derive(Error, Debug)]
8pub enum ToolError {
9    /// I.e. the llm calls the tool with the wrong arguments
10    #[error("arguments for tool failed to parse: {0:#}")]
11    WrongArguments(#[from] serde_json::Error),
12
13    /// Tool requires arguments but none were provided
14    #[error("arguments missing for tool {0:#}")]
15    MissingArguments(String),
16
17    /// Tool execution failed
18    #[error("tool execution failed: {0:#}")]
19    ExecutionFailed(#[from] CommandError),
20
21    #[error(transparent)]
22    Unknown(#[from] anyhow::Error),
23}
24
25type BoxedError = Box<dyn std::error::Error + Send + Sync>;
26
27#[derive(Error, Debug)]
28pub enum LanguageModelError {
29    #[error("Context length exceeded: {0}")]
30    ContextLengthExceeded(BoxedError),
31    #[error("Permanent error: {0}")]
32    PermanentError(BoxedError),
33    #[error("Transient error: {0}")]
34    TransientError(BoxedError),
35}
36
37impl LanguageModelError {
38    pub fn permanent(e: impl Into<BoxedError>) -> Self {
39        LanguageModelError::PermanentError(e.into())
40    }
41
42    pub fn transient(e: impl Into<BoxedError>) -> Self {
43        LanguageModelError::TransientError(e.into())
44    }
45
46    pub fn context_length_exceeded(e: impl Into<BoxedError>) -> Self {
47        LanguageModelError::ContextLengthExceeded(e.into())
48    }
49}
50
51impl From<BoxedError> for LanguageModelError {
52    fn from(e: BoxedError) -> Self {
53        LanguageModelError::PermanentError(e)
54    }
55}
56
57impl From<anyhow::Error> for LanguageModelError {
58    fn from(e: anyhow::Error) -> Self {
59        LanguageModelError::PermanentError(e.into())
60    }
61}
62
63// Make it easier to use the error in streaming functions
64
65impl From<LanguageModelError> for ChatCompletionStream {
66    fn from(val: LanguageModelError) -> Self {
67        Box::pin(futures_util::stream::once(async move { Err(val) }))
68    }
69}