Skip to main content

llm_api/
lib.rs

1//! Canonical model invocation and continuation contract. No Agent or transport implementation.
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4mod continuation;
5mod policy;
6pub use artifact_api::ArtifactUri;
7pub use continuation::Continuation;
8pub use policy::{
9    controls, input_modality_for_kind, input_modality_for_mime, normalize_capability_input,
10    normalize_constraint_input, normalize_input_token, payload_input_modalities, resolve,
11    BackendCapability, EffectiveGeneration, GenerationControls, GenerationParameters,
12    GenerationSupport, ModelCapabilities, DEFAULT_MAX_OUTPUT_TOKENS, INPUT_AUDIO, INPUT_FILE,
13    INPUT_IMAGE, INPUT_VIDEO, REASONING_EFFORT_LADDER,
14};
15
16/// Logical model use case resolved by the deployment's LLM implementation.
17#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
18#[serde(transparent)]
19pub struct UseCase(pub String);
20
21/// Caller-declared requirements. Listed input modalities and true flags require confirmed
22/// support; an empty `input` list and false flags impose no requirement.
23/// Adapters must not infer or override these declarations from message content.
24#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
25#[serde(deny_unknown_fields)]
26pub struct ModelConstraints {
27    /// Closed vocabulary: `image`, `video`, `audio`, `file`. `text` and `vision` are rejected.
28    #[serde(default)]
29    pub input: Vec<String>,
30    /// The model must support tool calls.
31    pub tool_calling: bool,
32    /// The model must support schema-constrained output.
33    pub structured_output: bool,
34}
35
36/// Role of a message in a model conversation.
37#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
38#[serde(rename_all = "snake_case")]
39#[derive(Default)]
40pub enum MessageRole {
41    /// Runtime-supplied instruction.
42    System,
43    /// User-supplied input.
44    #[default]
45    User,
46    /// Model output.
47    Assistant,
48    /// Tool execution output.
49    Tool,
50}
51
52/// One typed part of a model message.
53#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
54#[serde(tag = "type", rename_all = "snake_case")]
55#[serde(deny_unknown_fields)]
56pub enum ContentPart {
57    /// Plain text content.
58    Text {
59        /// Text value.
60        text: String,
61    },
62    /// Scope-owned content-addressed artifact managed by the application artifact service.
63    Artifact {
64        /// Canonical `meow-artifact://` URI.
65        uri: ArtifactUri,
66    },
67    /// A model-requested tool invocation.
68    ToolCall(ToolCall),
69    /// Result of an earlier tool invocation.
70    ToolResult {
71        /// Provider-neutral call identifier.
72        call_id: String,
73        /// Structured result payload.
74        result: Value,
75        /// Whether the tool execution failed.
76        is_error: bool,
77    },
78}
79
80/// Provider-neutral conversation message.
81#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct Message {
84    /// Speaker role.
85    pub role: MessageRole,
86    /// Ordered message content.
87    pub content: Vec<ContentPart>,
88    /// Private model continuation; never part of a user transcript.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub continuation: Option<Continuation>,
91}
92
93/// A callable function exposed to the model. Execution policy belongs to the caller.
94#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
95pub struct ToolDefinition {
96    pub name: String,
97    pub description: String,
98    pub input_schema: Value,
99}
100/// Tool call returned by an LLM.
101#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
102#[serde(deny_unknown_fields)]
103pub struct ToolCall {
104    /// Provider-neutral identifier used to correlate the result.
105    pub id: String,
106    /// Requested tool name.
107    pub name: String,
108    /// Structured arguments.
109    pub arguments: Value,
110}
111
112/// One logical LLM invocation.
113#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
114pub struct CompletionRequest {
115    /// Logical routing key resolved by the LLM adapter.
116    pub use_case: UseCase,
117
118    /// Conversation input.
119    pub messages: Vec<Message>,
120    /// Tools available to the model.
121    pub tools: Vec<ToolDefinition>,
122    /// Required model capabilities.
123    pub constraints: ModelConstraints,
124    /// Optional maximum number of output tokens.
125    pub max_output_tokens: Option<u32>,
126    /// Whether the caller requested sanitized diagnostic metadata.
127    pub diagnostics: bool,
128}
129
130/// Provider-neutral limits for one frozen logical model route.
131///
132/// `profile_key` is opaque to Runtime. Implementations must change it whenever the concrete
133/// model, tokenizer, or another input-serialization detail changes.
134#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
135pub struct ModelProfile {
136    /// Opaque stable identity of the frozen model and tokenizer route.
137    pub profile_key: String,
138    /// Maximum total context accepted by the concrete model.
139    pub context_window_tokens: u32,
140}
141
142/// Why a model invocation stopped.
143#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
144#[serde(rename_all = "snake_case")]
145#[derive(Default)]
146pub enum FinishReason {
147    /// The model completed normally.
148    #[default]
149    Stop,
150    /// The model requested one or more tools.
151    ToolCalls,
152    /// The configured output limit was reached.
153    Length,
154    /// The LLM adapter cannot map the provider result to a more specific reason.
155    Other,
156}
157
158/// Normalized token accounting reported by an implementation.
159#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
160pub struct TokenUsage {
161    /// Input token count.
162    pub input_tokens: u64,
163    /// Output token count.
164    pub output_tokens: u64,
165    /// Input tokens served from a provider cache when reported.
166    pub cached_input_tokens: Option<u64>,
167    /// Reasoning output tokens when reported separately.
168    pub reasoning_output_tokens: Option<u64>,
169    /// Provider-normalized billable credits consumed by this request.
170    pub credits: Option<u64>,
171}
172
173/// Provider-neutral completion returned to Runtime.
174#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
175pub struct Completion {
176    /// Model response message.
177    pub message: Message,
178    /// Normalized finish reason.
179    pub finish_reason: FinishReason,
180    /// Normalized token accounting.
181    pub usage: Option<TokenUsage>,
182    /// Optional sanitized diagnostics without credentials or provider internals.
183    pub diagnostics: Option<Value>,
184}
185
186pub mod service;
187
188impl MessageRole {
189    pub const fn as_str(self) -> &'static str {
190        match self {
191            Self::System => "system",
192            Self::User => "user",
193            Self::Assistant => "assistant",
194            Self::Tool => "tool",
195        }
196    }
197}
198
199impl Default for Message {
200    fn default() -> Self {
201        Self::text(MessageRole::User, "")
202    }
203}
204impl Message {
205    pub fn text(role: MessageRole, text: impl Into<String>) -> Self {
206        Self {
207            role,
208            content: vec![ContentPart::Text { text: text.into() }],
209            continuation: None,
210        }
211    }
212    pub fn text_content(&self) -> String {
213        self.content
214            .iter()
215            .filter_map(|part| match part {
216                ContentPart::Text { text } => Some(text.as_str()),
217                _ => None,
218            })
219            .collect::<Vec<_>>()
220            .join("\n")
221    }
222}
223
224impl TokenUsage {
225    pub fn total_tokens(self) -> u64 {
226        self.input_tokens.saturating_add(self.output_tokens)
227    }
228}
229impl Message {
230    pub fn with_artifacts(mut self, artifacts: impl IntoIterator<Item = ArtifactUri>) -> Self {
231        self.content.extend(
232            artifacts
233                .into_iter()
234                .map(|uri| ContentPart::Artifact { uri }),
235        );
236        self
237    }
238}
239
240/// Offline normative schema for persisted model messages.
241pub const MESSAGE_SCHEMA: &str = include_str!("../schema/message.v1.schema.json");