diff --git a/Cargo.lock b/Cargo.lock index df18f7c5e..4b3c2a847 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2721,6 +2721,8 @@ dependencies = [ "harness", "image", "llm-clients", + "minijinja", + "minijinja-contrib", "serde", "serde_json", "test-support", @@ -2862,6 +2864,24 @@ dependencies = [ "unicase", ] +[[package]] +name = "minijinja" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f5a04892e86ddb4fc254e9160835370b63a0d44042d3ab4725bc2dbcbab136" +dependencies = [ + "serde", +] + +[[package]] +name = "minijinja-contrib" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f804cfd81c146ff898cbf3455071c417e8745907c77f3d5058bd9691b9ace3b8" +dependencies = [ + "minijinja", +] + [[package]] name = "minimal-lexical" version = "0.2.1" diff --git a/crates/llm-runtime/Cargo.toml b/crates/llm-runtime/Cargo.toml index 4fb2b39f2..d8f6b6a71 100644 --- a/crates/llm-runtime/Cargo.toml +++ b/crates/llm-runtime/Cargo.toml @@ -18,6 +18,8 @@ tools = { path = "../tools" } [dev-dependencies] api-projection = { path = "../api-projection" } +minijinja = { version = "3.0.5", features = ["json", "loop_controls", "serde"] } +minijinja-contrib = { version = "3.0.5", features = ["pycompat"] } test-support = { path = "../test-support" } tokio = { version = "1", features = ["io-util", "macros", "net", "rt"] } vfs = { path = "../vfs" } diff --git a/crates/llm-runtime/src/anthropic_messages.rs b/crates/llm-runtime/src/anthropic_messages.rs index d5b27f87a..99d48477f 100644 --- a/crates/llm-runtime/src/anthropic_messages.rs +++ b/crates/llm-runtime/src/anthropic_messages.rs @@ -713,23 +713,13 @@ async fn materialize_system( entries: &[ContextEntry], cache_control: &Value, ) -> LlmAdapterResult> { - let mut parts = Vec::new(); - for entry in entries { - if matches!(entry.kind, ContextEntryKind::Instructions) { - let text = read_text(blobs, &entry.content.content_ref).await?; - let text = text.trim(); - if !text.is_empty() { - parts.push(text.to_owned()); - } - } - } - if parts.is_empty() { + let Some(text) = crate::system_prompt::collated_instructions(blobs, entries).await? else { return Ok(None); - } + }; Ok(Some(am::SystemContent::Blocks(vec![ am::ContentBlockParam::Text(am::TextBlockParam { r#type: "text".to_owned(), - text: parts.join("\n\n"), + text, cache_control: Some(cache_control.clone()), extra: Default::default(), }), diff --git a/crates/llm-runtime/src/lib.rs b/crates/llm-runtime/src/lib.rs index b1e7288a6..c16c8f83f 100644 --- a/crates/llm-runtime/src/lib.rs +++ b/crates/llm-runtime/src/lib.rs @@ -19,6 +19,7 @@ mod prompt_cache; pub mod provider_keys; pub mod result; pub mod secrets; +mod system_prompt; pub mod testing; pub use anthropic_messages::{ diff --git a/crates/llm-runtime/src/openai_completions.rs b/crates/llm-runtime/src/openai_completions.rs index e779b0d2d..abffa05fd 100644 --- a/crates/llm-runtime/src/openai_completions.rs +++ b/crates/llm-runtime/src/openai_completions.rs @@ -9,11 +9,12 @@ use std::{collections::BTreeMap, sync::Arc}; use async_trait::async_trait; use harness::{ CompactionPolicy, ContextCompactionRequest, ContextCompactionResult, ContextCompactionStatus, - ContextCompactionTask, ContextEntry, ContextEntryInput, ContextEntryKind, ContextEntrySource, - ContextMessageRole, LlmFinish, LlmGenerationFacts, LlmGenerationRequest, LlmGenerationResult, - LlmGenerationStatus, LlmRequest, LlmUsage, OPENAI_COMPLETIONS_COMPACTION_PROVIDER_KIND, - ObservedToolCall, ProviderApiKind, RemoteMcpExecution, RemoteMcpExposure, TokenEstimate, - TokenEstimateQuality, ToolCallId, ToolId, ToolKind, ToolName, storage::BlobStore, + ContextCompactionTask, ContextEntry, ContextEntryId, ContextEntryInput, ContextEntryKind, + ContextEntrySource, ContextMessageRole, LlmFinish, LlmGenerationFacts, LlmGenerationRequest, + LlmGenerationResult, LlmGenerationStatus, LlmRequest, LlmUsage, + OPENAI_COMPLETIONS_COMPACTION_PROVIDER_KIND, ObservedToolCall, ProviderApiKind, + RemoteMcpExecution, RemoteMcpExposure, TokenEstimate, TokenEstimateQuality, ToolCallId, ToolId, + ToolKind, ToolName, storage::BlobStore, }; use llm_clients::{ApiResponse, openai::completions as oai_c}; use serde_json::{Value, json}; @@ -436,8 +437,31 @@ async fn materialize_messages_tracked( let mut positions = RequestPositions::with_capacity(entries.len()); let mut last_assistant_source: Option = None; let mut media = crate::media::RequestMedia::prepare(blobs, entries).await?; + let mut deferred = Vec::new(); + + // Every dialect gets the instructions as one leading message, the way the + // other adapters send one system prompt. Chat templates of self-hosted + // models (Qwen among them) accept no other system message. + if let Some(text) = crate::system_prompt::collated_instructions(blobs, entries).await? { + messages.push(text_message(dialect.instruction_role(), text)); + } for entry in entries { + if matches!(entry.kind, ContextEntryKind::Instructions) { + positions.push((entry.entry_id, 0)); + continue; + } + // Held catalogs land once the tool exchange is over: never between an + // assistant's calls and their results, nor inside that assistant. + if !matches!( + entry.kind, + ContextEntryKind::ToolResult { .. } | ContextEntryKind::Catalog { .. } + ) && messages + .last() + .is_none_or(|message: &oai_c::CompletionMessage| message.role != "assistant") + { + flush_deferred(&mut messages, &mut positions, &mut deferred); + } match &entry.kind { ContextEntryKind::ToolCall { .. } => { require_completions_provider_kind(entry)?; @@ -535,6 +559,29 @@ async fn materialize_messages_tracked( last_assistant_source = (message.role == "assistant").then(|| entry.source.clone()); messages.push(message); } + // A catalog is context, not instructions: user text at its + // position, as on Anthropic. A refreshed catalog lands at the + // tail, so no system message ever follows the conversation. + ContextEntryKind::Catalog { .. } => { + reject_foreign_provider_kind(entry)?; + let message = text_message( + "user", + crate::catalog_prompts::stored_catalog_text( + blobs, + entry, + &entry.content.content_ref, + ) + .await?, + ); + // A user message may not split an assistant's tool calls + // from their results; it waits until the exchange ends. + if !deferred.is_empty() || in_tool_exchange(&messages) { + deferred.push((entry.entry_id, message)); + continue; + } + push_message(&mut messages, message); + last_assistant_source = None; + } _ => { reject_foreign_provider_kind(entry)?; let message = materialize_message(blobs, entry, dialect, &mut media).await?; @@ -545,9 +592,32 @@ async fn materialize_messages_tracked( } positions.push((entry.entry_id, messages.len().saturating_sub(1))); } + flush_deferred(&mut messages, &mut positions, &mut deferred); Ok((messages, positions)) } +fn in_tool_exchange(messages: &[oai_c::CompletionMessage]) -> bool { + messages.last().is_some_and(|message| { + message.role == "tool" + || (message.role == "assistant" + && message + .tool_calls + .as_ref() + .is_some_and(|calls| !calls.is_empty())) + }) +} + +fn flush_deferred( + messages: &mut Vec, + positions: &mut RequestPositions, + deferred: &mut Vec<(ContextEntryId, oai_c::CompletionMessage)>, +) { + for (entry_id, message) in deferred.drain(..) { + push_message(messages, message); + positions.push((entry_id, messages.len() - 1)); + } +} + // Reasoning and visible output have distinct provenance labels, but belong // to the same native assistant message when their run and turn agree. fn same_assistant_turn(left: &ContextEntrySource, right: &ContextEntrySource) -> bool { @@ -735,15 +805,6 @@ async fn materialize_message( ..Default::default() }) } - ContextEntryKind::Instructions => Ok(text_message( - dialect.instruction_role(), - read_text(blobs, &entry.content.content_ref).await?, - )), - ContextEntryKind::Catalog { .. } => Ok(text_message( - dialect.instruction_role(), - crate::catalog_prompts::stored_catalog_text(blobs, entry, &entry.content.content_ref) - .await?, - )), ContextEntryKind::ToolResult { call_id, .. } => Ok(oai_c::CompletionMessage { role: "tool".to_owned(), content: Some(oai_c::CompletionMessageContent::Text( @@ -752,7 +813,9 @@ async fn materialize_message( tool_call_id: Some(call_id.as_str().to_owned()), ..Default::default() }), - ContextEntryKind::ToolCall { .. } + ContextEntryKind::Instructions + | ContextEntryKind::Catalog { .. } + | ContextEntryKind::ToolCall { .. } | ContextEntryKind::ReasoningState | ContextEntryKind::ProviderOpaque | ContextEntryKind::McpApprovalResponse { .. } => { @@ -2974,4 +3037,586 @@ mod tests { [(1, 0), (2, 1), (3, 2)].map(|(id, index)| (ContextEntryId::new(id), index)) ); } + + const ALL_DIALECTS: [CompletionDialect; 4] = [ + CompletionDialect::OpenAi, + CompletionDialect::DeepSeek, + CompletionDialect::OpenRouter, + CompletionDialect::Compatible, + ]; + + fn text_entry( + id: u64, + kind: ContextEntryKind, + source: ContextEntrySource, + text: &BlobRef, + ) -> ContextEntry { + entry(id, kind, source, text.clone()) + } + + fn user_message(id: u64, run: u64, text: &BlobRef) -> ContextEntry { + text_entry( + id, + ContextEntryKind::Message { + role: ContextMessageRole::User, + }, + ContextEntrySource::RunInput { + run_id: RunId::new(run), + input_index: 0, + }, + text, + ) + } + + fn assistant_message(id: u64, run: u64, turn: u64, text: &BlobRef) -> ContextEntry { + text_entry( + id, + ContextEntryKind::Message { + role: ContextMessageRole::Assistant, + }, + ContextEntrySource::AssistantOutput { + run_id: RunId::new(run), + turn_id: TurnId::new(turn), + }, + text, + ) + } + + fn instructions(id: u64, text: &BlobRef) -> ContextEntry { + text_entry( + id, + ContextEntryKind::Instructions, + ContextEntrySource::ContextEdit, + text, + ) + } + + fn catalog(id: u64, text: &BlobRef, supersedes: Option) -> ContextEntry { + let mut catalog = text_entry( + id, + ContextEntryKind::Catalog { + title: "Bot directory".to_owned(), + }, + ContextEntrySource::ContextEdit, + text, + ); + catalog.supersedes = supersedes.map(ContextEntryId::new); + catalog + } + + async fn tool_call(blobs: &InMemoryBlobStore, id: u64, run: u64, turn: u64) -> ContextEntry { + let call_ref = put_json( + blobs, + &json!({ + "id": format!("call{id:05}"), + "type": "function", + "function": { "name": "read_file", "arguments": "{}" } + }), + ) + .await + .expect("call"); + let mut call = entry( + id, + ContextEntryKind::ToolCall { + call_id: ToolCallId::try_new(format!("call{id:05}")).expect("call id"), + name: ToolName::try_new("read_file").expect("tool name"), + }, + ContextEntrySource::AssistantOutput { + run_id: RunId::new(run), + turn_id: TurnId::new(turn), + }, + call_ref, + ); + call.content.media_type = Some(MEDIA_TYPE_JSON.to_owned()); + call.content.provider_kind = Some(OPENAI_COMPLETIONS_TOOL_CALL_PROVIDER_KIND.to_owned()); + call + } + + fn tool_result(id: u64, call: u64, run: u64, turn: u64, text: &BlobRef) -> ContextEntry { + text_entry( + id, + ContextEntryKind::ToolResult { + call_id: ToolCallId::try_new(format!("call{call:05}")).expect("call id"), + is_error: false, + }, + ContextEntrySource::Tool { + run_id: RunId::new(run), + turn_id: TurnId::new(turn), + batch_id: None, + }, + text, + ) + } + + async fn rendered( + blobs: &InMemoryBlobStore, + entries: &[ContextEntry], + dialect: CompletionDialect, + ) -> Vec { + materialize_messages(blobs, entries, dialect) + .await + .expect("materialize") + .iter() + .map(|message| serde_json::to_string(message).expect("json")) + .collect() + } + + /// Request N must be a byte-level prefix of request N+1, message for + /// message, so a provider's prefix cache (OpenAI, vLLM, SGLang) keeps + /// everything N already sent. + async fn assert_prefix_kept( + blobs: &InMemoryBlobStore, + before: &[ContextEntry], + appended: &[ContextEntry], + ) { + let after = [before, appended].concat(); + for dialect in ALL_DIALECTS { + let first = rendered(blobs, before, dialect).await; + let second = rendered(blobs, &after, dialect).await; + assert!( + second.len() >= first.len() && second[..first.len()] == first[..], + "{dialect:?}: request N is not a prefix of request N+1\nN: {first:#?}\nN+1: {second:#?}" + ); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn every_dialect_sends_one_leading_instruction_message_and_catalogs_as_user() { + let blobs = InMemoryBlobStore::new(); + let base = blobs.insert_text("Be precise.").await; + let profile = blobs.insert_text(" You review code.\n").await; + let empty = blobs.insert_text(" ").await; + let directory = blobs.insert_text("- helper").await; + let hello = blobs.insert_text("Hello").await; + let entries = vec![ + instructions(1, &base), + instructions(2, &profile), + instructions(3, &empty), + catalog(4, &directory, None), + user_message(5, 1, &hello), + ]; + + for dialect in ALL_DIALECTS { + let (messages, positions) = materialize_messages_tracked(&blobs, &entries, dialect) + .await + .expect("materialize"); + assert_eq!( + serde_json::to_value(&messages).expect("json"), + json!([ + { "role": dialect.instruction_role(), "content": "Be precise.\n\nYou review code." }, + { "role": "user", "content": [ + { "type": "text", "text": "Bot directory:\n\n- helper" }, + { "type": "text", "text": "Hello" } + ] } + ]), + "{dialect:?}" + ); + assert_eq!( + positions, + [(1, 0), (2, 0), (3, 0), (4, 1), (5, 1)] + .map(|(id, index)| (ContextEntryId::new(id), index)) + ); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn no_system_message_follows_the_conversation() { + let blobs = InMemoryBlobStore::new(); + let base = blobs.insert_text("Be precise.").await; + let late = blobs.insert_text("Late layer.").await; + let directory = blobs.insert_text("- helper").await; + let refreshed = blobs.insert_text("- helper\n- reviewer").await; + let hello = blobs.insert_text("Hello").await; + let answer = blobs.insert_text("Hi").await; + let entries = vec![ + instructions(1, &base), + catalog(2, &directory, None), + user_message(3, 1, &hello), + assistant_message(4, 1, 1, &answer), + // Out of planned order on purpose: instructions still lead. + instructions(5, &late), + catalog(6, &refreshed, Some(2)), + user_message(7, 2, &hello), + ]; + + for dialect in ALL_DIALECTS { + let messages = materialize_messages(&blobs, &entries, dialect) + .await + .expect("materialize"); + let roles = messages + .iter() + .map(|message| message.role.as_str()) + .collect::>(); + let leading = dialect.instruction_role(); + assert_eq!(roles, [leading, "user", "assistant", "user"], "{dialect:?}"); + assert_eq!(messages[0].text(), "Be precise.\n\nLate layer."); + assert!( + messages[3] + .text() + .starts_with(crate::catalog_prompts::CATALOG_UPDATE_HEADER), + "{dialect:?}: the refreshed catalog announces itself" + ); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn a_catalog_arriving_mid_tool_exchange_waits_for_the_results() { + let blobs = InMemoryBlobStore::new(); + let directory = blobs.insert_text("- helper").await; + let hello = blobs.insert_text("Hello").await; + let contents = blobs.insert_text("contents").await; + let entries = vec![ + user_message(1, 1, &hello), + tool_call(&blobs, 2, 1, 1).await, + catalog(3, &directory, None), + tool_result(4, 2, 1, 1, &contents), + ]; + + for dialect in ALL_DIALECTS { + let (messages, positions) = materialize_messages_tracked(&blobs, &entries, dialect) + .await + .expect("materialize"); + let roles = messages + .iter() + .map(|message| message.role.as_str()) + .collect::>(); + assert_eq!(roles, ["user", "assistant", "tool", "user"], "{dialect:?}"); + assert_eq!(messages[3].text(), "Bot directory:\n\n- helper"); + assert_eq!( + positions, + [(1, 0), (2, 1), (4, 2), (3, 3)] + .map(|(id, index)| (ContextEntryId::new(id), index)) + ); + } + } + + #[tokio::test(flavor = "current_thread")] + async fn the_prefix_holds_across_a_new_turn_a_tool_round_trip_and_a_catalog_refresh() { + let blobs = InMemoryBlobStore::new(); + let base = blobs.insert_text("Be precise.").await; + let profile = blobs.insert_text("You review code.").await; + let directory = blobs.insert_text("- helper").await; + let refreshed = blobs.insert_text("- helper\n- reviewer").await; + let hello = blobs.insert_text("Hello").await; + let answer = blobs.insert_text("Hi").await; + let contents = blobs.insert_text("contents").await; + + // Turn 1 of run 1. + let first = vec![ + instructions(1, &base), + instructions(2, &profile), + catalog(3, &directory, None), + user_message(4, 1, &hello), + ]; + // The model calls a tool; the next request carries the result. + let tool_round = vec![ + tool_call(&blobs, 5, 1, 1).await, + tool_result(6, 5, 1, 1, &contents), + ]; + assert_prefix_kept(&blobs, &first, &tool_round).await; + + // Run 2: the catalog is refreshed before the next user message. + let second = [ + first.clone(), + tool_round.clone(), + vec![assistant_message(7, 1, 2, &answer)], + ] + .concat(); + let refresh = vec![catalog(8, &refreshed, Some(3)), user_message(9, 2, &hello)]; + assert_prefix_kept(&blobs, &second, &refresh).await; + + // A catalog published while a tool call is open. + let third = [second.clone(), refresh.clone()].concat(); + let mid_exchange = vec![ + tool_call(&blobs, 10, 2, 1).await, + catalog(11, &refreshed, Some(8)), + tool_result(12, 10, 2, 1, &contents), + ]; + assert_prefix_kept(&blobs, &third, &mid_exchange).await; + let fourth = [third, mid_exchange].concat(); + assert_prefix_kept( + &blobs, + &fourth, + &[ + assistant_message(13, 2, 2, &answer), + user_message(14, 3, &hello), + ], + ) + .await; + } + + #[tokio::test(flavor = "current_thread")] + async fn every_adapter_collates_the_same_system_prompt() { + let blobs = InMemoryBlobStore::new(); + let base = blobs.insert_text("Be precise.\n").await; + let empty = blobs.insert_text("").await; + let profile = blobs.insert_text("You review code.").await; + let entries = vec![ + instructions(1, &base), + instructions(2, &empty), + instructions(3, &profile), + ]; + let collated = crate::system_prompt::collated_instructions(&blobs, &entries) + .await + .expect("collate"); + assert_eq!(collated.as_deref(), Some("Be precise.\n\nYou review code.")); + for dialect in ALL_DIALECTS { + let messages = materialize_messages(&blobs, &entries, dialect) + .await + .expect("materialize"); + assert_eq!(messages.len(), 1); + assert_eq!(Some(messages[0].text()), collated); + } + } + + /// Real chat templates of open models, rendered the way vLLM renders them. + mod chat_templates { + use super::*; + use minijinja::{Environment, Error, ErrorKind, context}; + + const TEMPLATES: [(&str, &str); 5] = [ + ( + "qwen3.5", + include_str!("../tests/fixtures/chat_templates/qwen3.5.jinja"), + ), + ( + "qwen3", + include_str!("../tests/fixtures/chat_templates/qwen3.jinja"), + ), + ( + "qwen2.5", + include_str!("../tests/fixtures/chat_templates/qwen2.5.jinja"), + ), + ( + "gpt-oss", + include_str!("../tests/fixtures/chat_templates/gpt-oss.jinja"), + ), + ( + "mistral-v0.3", + include_str!("../tests/fixtures/chat_templates/mistral-v0.3.jinja"), + ), + ]; + + /// Templates that move the system prompt next to the newest user + /// message, so no client can keep their rendered prefix stable. + const MOVES_SYSTEM_PROMPT: [&str; 1] = ["mistral-v0.3"]; + + /// Templates that render earlier assistant turns differently once a + /// newer user message exists. + const RERENDERS_PAST_TURNS: [&str; 1] = ["qwen3.5"]; + + fn environment() -> Environment<'static> { + let mut env = Environment::new(); + env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback); + env.add_function( + "raise_exception", + |message: String| -> Result { + Err(Error::new(ErrorKind::InvalidOperation, message)) + }, + ); + env.add_function("strftime_now", |_format: String| "2026-11-18".to_owned()); + for (name, source) in TEMPLATES { + env.add_template(name, source).expect("template parses"); + } + env + } + + /// The request messages as a server hands them to the template: text + /// parts joined into one string, null fields left out, tool-call + /// arguments parsed. + fn template_messages(messages: &[oai_c::CompletionMessage]) -> Vec { + messages + .iter() + .map(|message| { + let mut value = serde_json::to_value(message).expect("json"); + if let Some(parts) = value["content"].as_array() { + let text = parts + .iter() + .filter_map(|part| part["text"].as_str()) + .collect::>() + .join("\n"); + value["content"] = Value::String(text); + } + if let Some(object) = value.as_object_mut() { + object.retain(|_, field| !field.is_null()); + } + if let Some(calls) = value.get_mut("tool_calls").and_then(Value::as_array_mut) { + for call in calls { + let arguments = call["function"]["arguments"].as_str().unwrap_or("{}"); + call["function"]["arguments"] = + serde_json::from_str(arguments).expect("arguments"); + } + } + value + }) + .collect() + } + + fn render(env: &Environment, name: &str, messages: &[Value]) -> Result { + render_with(env, name, messages, true) + } + + fn render_with( + env: &Environment, + name: &str, + messages: &[Value], + add_generation_prompt: bool, + ) -> Result { + let tools = json!([{ + "type": "function", + "function": { + "name": "read_file", + "description": "Read a file.", + "parameters": { "type": "object", "properties": {} } + } + }]); + env.get_template(name).expect("template").render(context! { + messages => minijinja::Value::from(minijinja::value::Serde(messages)), + tools => minijinja::Value::from(minijinja::value::Serde(&tools)), + add_generation_prompt => add_generation_prompt, + bos_token => "", + eos_token => "", + }) + } + + /// A session's requests as it grows: instructions in layers, a + /// catalog, a tool round trip, a refreshed catalog and a second run. + async fn session_requests(blobs: &InMemoryBlobStore) -> Vec> { + let base = blobs.insert_text("Be precise.").await; + let profile = blobs.insert_text("You review code.").await; + let environment = blobs.insert_text("You work in /data/workspace.").await; + let directory = blobs.insert_text("- helper").await; + let refreshed = blobs.insert_text("- helper\n- reviewer").await; + let hello = blobs.insert_text("Hello").await; + let answer = blobs.insert_text("Hi").await; + let contents = blobs.insert_text("contents").await; + + let first = vec![ + instructions(1, &base), + instructions(2, &profile), + instructions(3, &environment), + catalog(4, &directory, None), + user_message(5, 1, &hello), + ]; + let second = [ + first.clone(), + vec![ + tool_call(blobs, 6, 1, 1).await, + tool_result(7, 6, 1, 1, &contents), + ], + ] + .concat(); + let third = [ + second.clone(), + vec![ + assistant_message(8, 1, 2, &answer), + catalog(9, &refreshed, Some(4)), + user_message(10, 2, &hello), + ], + ] + .concat(); + vec![first, second, third] + } + + #[tokio::test(flavor = "current_thread")] + async fn every_template_accepts_every_dialects_requests() { + let env = environment(); + let blobs = InMemoryBlobStore::new(); + for entries in session_requests(&blobs).await { + // OpenAI and OpenRouter send `developer`; they never reach a + // self-hosted template. + for dialect in [CompletionDialect::Compatible, CompletionDialect::DeepSeek] { + let messages = materialize_messages(&blobs, &entries, dialect) + .await + .expect("materialize"); + let messages = template_messages(&messages); + for (name, _) in TEMPLATES { + if let Err(error) = render(&env, name, &messages) { + panic!("{name} rejects the {dialect:?} request: {error:#}"); + } + } + } + } + } + + /// Request N+1 must render as request N plus new text, so a server's + /// prefix cache (vLLM, SGLang, llama.cpp) keeps what N computed. Some + /// templates re-render earlier assistant turns once a new user message + /// arrives (Qwen drops the empty think block); for those the cache is + /// kept up to the previous request's last user message, which is all + /// any client can get from them. + #[tokio::test(flavor = "current_thread")] + async fn every_rendered_request_extends_the_previous_one() { + let env = environment(); + let blobs = InMemoryBlobStore::new(); + let requests = session_requests(&blobs).await; + for (name, _) in TEMPLATES { + if MOVES_SYSTEM_PROMPT.contains(&name) { + continue; + } + let mut previous: Option> = None; + for entries in &requests { + let messages = template_messages( + &materialize_messages(&blobs, entries, CompletionDialect::Compatible) + .await + .expect("materialize"), + ); + let rendered = render(&env, name, &messages).expect("render"); + if let Some(previous) = previous { + let last_user = previous + .iter() + .rposition(|message| message["role"] == "user") + .expect("a user message"); + let new_run = messages[previous.len()..] + .iter() + .any(|message| message["role"] == "user"); + let stable = if new_run && RERENDERS_PAST_TURNS.contains(&name) { + render_with(&env, name, &previous[..=last_user], false) + } else { + render(&env, name, &previous) + } + .expect("render"); + let kept = stable + .chars() + .zip(rendered.chars()) + .take_while(|(left, right)| left == right) + .count(); + assert!( + rendered.starts_with(&stable), + "{name}: the next request rewrites the rendered prompt after {kept} of {} characters\n--- before\n{stable}\n--- after\n{rendered}", + stable.chars().count() + ); + } + previous = Some(messages); + } + } + } + + /// The message shape this change replaces: one system message per + /// instruction layer and per catalog. The templates must reject it, + /// or the test above would not catch a regression. + #[test] + fn the_old_shape_is_rejected_where_it_broke() { + let env = environment(); + let messages = [ + json!({ "role": "system", "content": "Be precise." }), + json!({ "role": "system", "content": "Bot directory:\n\n- helper" }), + json!({ "role": "user", "content": "Hello" }), + json!({ "role": "assistant", "content": "Hi" }), + json!({ "role": "system", "content": "Bot directory:\n\n- helper\n- reviewer" }), + json!({ "role": "user", "content": "Hello" }), + ]; + let qwen = render(&env, "qwen3.5", &messages).expect_err("qwen3.5 rejects it"); + assert!( + qwen.to_string() + .contains("System message must be at the beginning."), + "{qwen:#}" + ); + let mistral = render(&env, "mistral-v0.3", &messages).expect_err("mistral rejects it"); + assert!( + mistral.to_string().contains("roles must alternate"), + "{mistral:#}" + ); + } + } } diff --git a/crates/llm-runtime/src/openai_responses.rs b/crates/llm-runtime/src/openai_responses.rs index 384d56646..965f375cb 100644 --- a/crates/llm-runtime/src/openai_responses.rs +++ b/crates/llm-runtime/src/openai_responses.rs @@ -533,21 +533,9 @@ async fn materialize_instructions( blobs: &dyn BlobStore, entries: &[ContextEntry], ) -> LlmAdapterResult> { - let mut parts = Vec::new(); - for entry in entries { - if matches!(entry.kind, ContextEntryKind::Instructions) { - let text = read_text(blobs, &entry.content.content_ref).await?; - let text = text.trim(); - if !text.is_empty() { - parts.push(text.to_owned()); - } - } - } - if parts.is_empty() { - Ok(None) - } else { - Ok(Some(Value::String(parts.join("\n\n")))) - } + Ok(crate::system_prompt::collated_instructions(blobs, entries) + .await? + .map(Value::String)) } async fn materialize_input_items( diff --git a/crates/llm-runtime/src/system_prompt.rs b/crates/llm-runtime/src/system_prompt.rs new file mode 100644 index 000000000..2fe54f38c --- /dev/null +++ b/crates/llm-runtime/src/system_prompt.rs @@ -0,0 +1,39 @@ +//! The system prompt, built the same way for every provider. +//! +//! The harness plans instruction entries first, ordered by key so the most +//! stable layers come first. Every adapter joins them into a single text: one +//! Anthropic system block, the Responses `instructions` field, or one leading +//! Chat Completions `system`/`developer` message. Self-hosted chat templates +//! (Qwen among them) accept at most one system message, and only as the first +//! message, so a single text is also the one shape every template renders. +//! +//! Joining keeps the layers in order, so a prompt prefix cache behaves as it +//! would with one message per layer: a change in one layer invalidates that +//! layer and everything after it, nothing before it. + +use harness::{ContextEntry, ContextEntryKind, storage::BlobStore}; + +use crate::{blob_io::read_text, error::LlmAdapterResult}; + +/// Separator between instruction layers. +const LAYER_SEPARATOR: &str = "\n\n"; + +/// All instruction entries in planned order, each trimmed, empty ones +/// skipped, joined by a blank line. `None` when no layer has text, since +/// providers reject an empty system prompt. +pub(crate) async fn collated_instructions( + blobs: &dyn BlobStore, + entries: &[ContextEntry], +) -> LlmAdapterResult> { + let mut layers = Vec::new(); + for entry in entries { + if matches!(entry.kind, ContextEntryKind::Instructions) { + let text = read_text(blobs, &entry.content.content_ref).await?; + let text = text.trim(); + if !text.is_empty() { + layers.push(text.to_owned()); + } + } + } + Ok((!layers.is_empty()).then(|| layers.join(LAYER_SEPARATOR))) +} diff --git a/crates/llm-runtime/tests/fixtures/chat_templates/README.md b/crates/llm-runtime/tests/fixtures/chat_templates/README.md new file mode 100644 index 000000000..444d9deb8 --- /dev/null +++ b/crates/llm-runtime/tests/fixtures/chat_templates/README.md @@ -0,0 +1,21 @@ +# Chat templates of open models + +The Jinja chat templates that self-hosted servers (vLLM, SGLang, llama.cpp +with `--jinja`) apply to Chat Completions requests. The conformance tests in +`src/openai_completions.rs` (`chat_templates`) render real request shapes +through them, so a request a template rejects, or a request whose rendered +prefix changes between turns, fails without a GPU. + +Each file is the `chat_template` of the model's `tokenizer_config.json` (or its +`chat_template.jinja`) at the pinned revision, unchanged. + +| File | Model | Revision | License | +| --- | --- | --- | --- | +| `qwen3.5.jinja` | `Qwen/Qwen3.5-9B` | `c202236235762e1c871ad0ccb60c8ee5ba337b9a` | Apache-2.0 | +| `qwen3.jinja` | `Qwen/Qwen3-8B` | `b968826d9c46dd6066d109eabc6255188de91218` | Apache-2.0 | +| `qwen2.5.jinja` | `Qwen/Qwen2.5-7B-Instruct` | `a09a35458c702b33eeacc393d103063234e8bc28` | Apache-2.0 | +| `gpt-oss.jinja` | `openai/gpt-oss-20b` | `6cee5e81ee83917806bbde320786a8fb61efebee` | Apache-2.0 | +| `mistral-v0.3.jinja` | `mistralai/Mistral-7B-Instruct-v0.3` | `c170c708c41dac9275d15a8fff4eca08d52bab71` | Apache-2.0 | + +Llama and Gemma templates are left out: those models are gated behind their +own licenses. Templates without tool calling (Phi-4) are left out too. diff --git a/crates/llm-runtime/tests/fixtures/chat_templates/gpt-oss.jinja b/crates/llm-runtime/tests/fixtures/chat_templates/gpt-oss.jinja new file mode 100644 index 000000000..dc7bb1192 --- /dev/null +++ b/crates/llm-runtime/tests/fixtures/chat_templates/gpt-oss.jinja @@ -0,0 +1,331 @@ +{#- + In addition to the normal inputs of `messages` and `tools`, this template also accepts the + following kwargs: + - "builtin_tools": A list, can contain "browser" and/or "python". + - "model_identity": A string that optionally describes the model identity. + - "reasoning_effort": A string that describes the reasoning effort, defaults to "medium". + #} + +{#- Tool Definition Rendering ============================================== #} +{%- macro render_typescript_type(param_spec, required_params, is_nullable=false) -%} + {%- if param_spec.type == "array" -%} + {%- if param_spec['items'] -%} + {%- if param_spec['items']['type'] == "string" -%} + {{- "string[]" }} + {%- elif param_spec['items']['type'] == "number" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "integer" -%} + {{- "number[]" }} + {%- elif param_spec['items']['type'] == "boolean" -%} + {{- "boolean[]" }} + {%- else -%} + {%- set inner_type = render_typescript_type(param_spec['items'], required_params) -%} + {%- if inner_type == "object | object" or inner_type|length > 50 -%} + {{- "any[]" }} + {%- else -%} + {{- inner_type + "[]" }} + {%- endif -%} + {%- endif -%} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- else -%} + {{- "any[]" }} + {%- if param_spec.nullable -%} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type is defined and param_spec.type is iterable and param_spec.type is not string and param_spec.type is not mapping and param_spec.type[0] is defined -%} + {#- Handle array of types like ["object", "object"] from Union[dict, list] #} + {%- if param_spec.type | length > 1 -%} + {{- param_spec.type | join(" | ") }} + {%- else -%} + {{- param_spec.type[0] }} + {%- endif -%} + {%- elif param_spec.oneOf -%} + {#- Handle oneOf schemas - check for complex unions and fallback to any #} + {%- set has_object_variants = false -%} + {%- for variant in param_spec.oneOf -%} + {%- if variant.type == "object" -%} + {%- set has_object_variants = true -%} + {%- endif -%} + {%- endfor -%} + {%- if has_object_variants and param_spec.oneOf|length > 1 -%} + {{- "any" }} + {%- else -%} + {%- for variant in param_spec.oneOf -%} + {{- render_typescript_type(variant, required_params) -}} + {%- if variant.description %} + {{- "// " + variant.description }} + {%- endif -%} + {%- if variant.default is defined %} + {{ "// default: " + variant.default|tojson }} + {%- endif -%} + {%- if not loop.last %} + {{- " | " }} + {% endif -%} + {%- endfor -%} + {%- endif -%} + {%- elif param_spec.type == "string" -%} + {%- if param_spec.enum -%} + {{- '"' + param_spec.enum|join('" | "') + '"' -}} + {%- else -%} + {{- "string" }} + {%- if param_spec.nullable %} + {{- " | null" }} + {%- endif -%} + {%- endif -%} + {%- elif param_spec.type == "number" -%} + {{- "number" }} + {%- elif param_spec.type == "integer" -%} + {{- "number" }} + {%- elif param_spec.type == "boolean" -%} + {{- "boolean" }} + + {%- elif param_spec.type == "object" -%} + {%- if param_spec.properties -%} + {{- "{\n" }} + {%- for prop_name, prop_spec in param_spec.properties.items() -%} + {{- prop_name -}} + {%- if prop_name not in (param_spec.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{ render_typescript_type(prop_spec, param_spec.required or []) }} + {%- if not loop.last -%} + {{-", " }} + {%- endif -%} + {%- endfor -%} + {{- "}" }} + {%- else -%} + {{- "object" }} + {%- endif -%} + {%- else -%} + {{- "any" }} + {%- endif -%} +{%- endmacro -%} + +{%- macro render_tool_namespace(namespace_name, tools) -%} + {{- "## " + namespace_name + "\n\n" }} + {{- "namespace " + namespace_name + " {\n\n" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- "// " + tool.description + "\n" }} + {{- "type "+ tool.name + " = " }} + {%- if tool.parameters and tool.parameters.properties %} + {{- "(_: {\n" }} + {%- for param_name, param_spec in tool.parameters.properties.items() %} + {%- if param_spec.description %} + {{- "// " + param_spec.description + "\n" }} + {%- endif %} + {{- param_name }} + {%- if param_name not in (tool.parameters.required or []) -%} + {{- "?" }} + {%- endif -%} + {{- ": " }} + {{- render_typescript_type(param_spec, tool.parameters.required or []) }} + {%- if param_spec.default is defined -%} + {%- if param_spec.enum %} + {{- ", // default: " + param_spec.default }} + {%- elif param_spec.oneOf %} + {{- "// default: " + param_spec.default }} + {%- else %} + {{- ", // default: " + param_spec.default|tojson }} + {%- endif -%} + {%- endif -%} + {%- if not loop.last %} + {{- ",\n" }} + {%- else %} + {{- ",\n" }} + {%- endif -%} + {%- endfor %} + {{- "}) => any;\n\n" }} + {%- else -%} + {{- "() => any;\n\n" }} + {%- endif -%} + {%- endfor %} + {{- "} // namespace " + namespace_name }} +{%- endmacro -%} + +{%- macro render_builtin_tools(browser_tool, python_tool) -%} + {%- if browser_tool %} + {{- "## browser\n\n" }} + {{- "// Tool for browsing.\n" }} + {{- "// The `cursor` appears in brackets before each browsing display: `[{cursor}]`.\n" }} + {{- "// Cite information from the tool using the following format:\n" }} + {{- "// `【{cursor}†L{line_start}(-L{line_end})?】`, for example: `【6†L9-L11】` or `【8†L3】`.\n" }} + {{- "// Do not quote more than 10 words directly from the tool output.\n" }} + {{- "// sources=web (default: web)\n" }} + {{- "namespace browser {\n\n" }} + {{- "// Searches for information related to `query` and displays `topn` results.\n" }} + {{- "type search = (_: {\n" }} + {{- "query: string,\n" }} + {{- "topn?: number, // default: 10\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Opens the link `id` from the page indicated by `cursor` starting at line number `loc`, showing `num_lines` lines.\n" }} + {{- "// Valid link ids are displayed with the formatting: `【{id}†.*】`.\n" }} + {{- "// If `cursor` is not provided, the most recent page is implied.\n" }} + {{- "// If `id` is a string, it is treated as a fully qualified URL associated with `source`.\n" }} + {{- "// If `loc` is not provided, the viewport will be positioned at the beginning of the document or centered on the most relevant passage, if available.\n" }} + {{- "// Use this function without `id` to scroll to a new location of an opened page.\n" }} + {{- "type open = (_: {\n" }} + {{- "id?: number | string, // default: -1\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "loc?: number, // default: -1\n" }} + {{- "num_lines?: number, // default: -1\n" }} + {{- "view_source?: boolean, // default: false\n" }} + {{- "source?: string,\n" }} + {{- "}) => any;\n\n" }} + {{- "// Finds exact matches of `pattern` in the current page, or the page given by `cursor`.\n" }} + {{- "type find = (_: {\n" }} + {{- "pattern: string,\n" }} + {{- "cursor?: number, // default: -1\n" }} + {{- "}) => any;\n\n" }} + {{- "} // namespace browser\n\n" }} + {%- endif -%} + + {%- if python_tool %} + {{- "## python\n\n" }} + {{- "Use this tool to execute Python code in your chain of thought. The code will not be shown to the user. This tool should be used for internal reasoning, but not for code that is intended to be visible to the user (e.g. when creating plots, tables, or files).\n\n" }} + {{- "When you send a message containing Python code to python, it will be executed in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 120.0 seconds. The drive at '/mnt/data' can be used to save and persist user files. Internet access for this session is UNKNOWN. Depends on the cluster.\n\n" }} + {%- endif -%} +{%- endmacro -%} + +{#- System Message Construction ============================================ #} +{%- macro build_system_message() -%} + {%- if model_identity is not defined %} + {%- set model_identity = "You are ChatGPT, a large language model trained by OpenAI." %} + {%- endif %} + {{- model_identity + "\n" }} + {{- "Knowledge cutoff: 2024-06\n" }} + {{- "Current date: " + strftime_now("%Y-%m-%d") + "\n\n" }} + {%- if reasoning_effort is not defined %} + {%- set reasoning_effort = "medium" %} + {%- endif %} + {{- "Reasoning: " + reasoning_effort + "\n\n" }} + {%- if builtin_tools %} + {{- "# Tools\n\n" }} + {%- set available_builtin_tools = namespace(browser=false, python=false) %} + {%- for tool in builtin_tools %} + {%- if tool == "browser" %} + {%- set available_builtin_tools.browser = true %} + {%- elif tool == "python" %} + {%- set available_builtin_tools.python = true %} + {%- endif %} + {%- endfor %} + {{- render_builtin_tools(available_builtin_tools.browser, available_builtin_tools.python) }} + {%- endif -%} + {{- "# Valid channels: analysis, commentary, final. Channel must be included for every message." }} + {%- if tools -%} + {{- "\nCalls to these tools must go to the commentary channel: 'functions'." }} + {%- endif -%} +{%- endmacro -%} + +{#- Main Template Logic ================================================= #} +{#- Set defaults #} + +{#- Render system message #} +{{- "<|start|>system<|message|>" }} +{{- build_system_message() }} +{{- "<|end|>" }} + +{#- Extract developer message #} +{%- if messages[0].role == "developer" or messages[0].role == "system" %} + {%- set developer_message = messages[0].content %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set developer_message = "" %} + {%- set loop_messages = messages %} +{%- endif %} + +{#- Render developer message #} +{%- if developer_message or tools %} + {{- "<|start|>developer<|message|>" }} + {%- if developer_message %} + {{- "# Instructions\n\n" }} + {{- developer_message }} + {{- "\n\n" }} + {%- endif %} + {%- if tools -%} + {{- "# Tools\n\n" }} + {{- render_tool_namespace("functions", tools) }} + {%- endif -%} + {{- "<|end|>" }} +{%- endif %} + +{#- Render messages #} +{%- set last_tool_call = namespace(name=none) %} +{%- for message in loop_messages -%} + {#- At this point only assistant/user/tool messages should remain #} + {%- if message.role == 'assistant' -%} + {#- Checks to ensure the messages are being passed in the format we expect #} + {%- if "content" in message %} + {%- if "<|channel|>analysis<|message|>" in message.content or "<|channel|>final<|message|>" in message.content %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the content field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "thinking" in message %} + {%- if "<|channel|>analysis<|message|>" in message.thinking or "<|channel|>final<|message|>" in message.thinking %} + {{- raise_exception("You have passed a message containing <|channel|> tags in the thinking field. Instead of doing this, you should pass analysis messages (the string between '<|message|>' and '<|end|>') in the 'thinking' field, and final messages (the string between '<|message|>' and '<|end|>') in the 'content' field.") }} + {%- endif %} + {%- endif %} + {%- if "tool_calls" in message %} + {#- We need very careful handling here - we want to drop the tool call analysis message if the model #} + {#- has output a later <|final|> message, but otherwise we want to retain it. This is the only case #} + {#- when we render CoT/analysis messages in inference. #} + {%- set future_final_message = namespace(found=false) %} + {%- for future_message in loop_messages[loop.index:] %} + {%- if future_message.role == 'assistant' and "tool_calls" not in future_message %} + {%- set future_final_message.found = true %} + {%- endif %} + {%- endfor %} + {#- We assume max 1 tool call per message, and so we infer the tool call name #} + {#- in "tool" messages from the most recent assistant tool call name #} + {%- set tool_call = message.tool_calls[0] %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if message.content and message.thinking %} + {{- raise_exception("Cannot pass both content and thinking in an assistant message with tool calls! Put the analysis message in one or the other, but not both.") }} + {%- elif message.content and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.content + "<|end|>" }} + {%- elif message.thinking and not future_final_message.found %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {{- "<|start|>assistant to=" }} + {{- "functions." + tool_call.name + "<|channel|>commentary " }} + {{- (tool_call.content_type if tool_call.content_type is defined else "json") + "<|message|>" }} + {{- tool_call.arguments|tojson }} + {{- "<|call|>" }} + {%- set last_tool_call.name = tool_call.name %} + {%- elif loop.last and not add_generation_prompt %} + {#- Only render the CoT if the final turn is an assistant turn and add_generation_prompt is false #} + {#- This is a situation that should only occur in training, never in inference. #} + {%- if "thinking" in message %} + {{- "<|start|>assistant<|channel|>analysis<|message|>" + message.thinking + "<|end|>" }} + {%- endif %} + {#- <|return|> indicates the end of generation, but <|end|> does not #} + {#- <|return|> should never be an input to the model, but we include it as the final token #} + {#- when training, so the model learns to emit it. #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|return|>" }} + {%- else %} + {#- CoT is dropped during all previous turns, so we never render it for inference #} + {{- "<|start|>assistant<|channel|>final<|message|>" + message.content + "<|end|>" }} + {%- set last_tool_call.name = none %} + {%- endif %} + {%- elif message.role == 'tool' -%} + {%- if last_tool_call.name is none %} + {{- raise_exception("Message has tool role, but there was no previous assistant message with a tool call!") }} + {%- endif %} + {{- "<|start|>functions." + last_tool_call.name }} + {{- " to=assistant<|channel|>commentary<|message|>" + message.content|tojson + "<|end|>" }} + {%- elif message.role == 'user' -%} + {{- "<|start|>user<|message|>" + message.content + "<|end|>" }} + {%- endif -%} +{%- endfor -%} + +{#- Generation prompt #} +{%- if add_generation_prompt -%} +<|start|>assistant +{%- endif -%} \ No newline at end of file diff --git a/crates/llm-runtime/tests/fixtures/chat_templates/mistral-v0.3.jinja b/crates/llm-runtime/tests/fixtures/chat_templates/mistral-v0.3.jinja new file mode 100644 index 000000000..0bab084a4 --- /dev/null +++ b/crates/llm-runtime/tests/fixtures/chat_templates/mistral-v0.3.jinja @@ -0,0 +1,87 @@ +{%- if messages[0]["role"] == "system" %} + {%- set system_message = messages[0]["content"] %} + {%- set loop_messages = messages[1:] %} +{%- else %} + {%- set loop_messages = messages %} +{%- endif %} +{%- if not tools is defined %} + {%- set tools = none %} +{%- endif %} +{%- set user_messages = loop_messages | selectattr("role", "equalto", "user") | list %} + +{#- This block checks for alternating user/assistant messages, skipping tool calling messages #} +{%- set ns = namespace() %} +{%- set ns.index = 0 %} +{%- for message in loop_messages %} + {%- if not (message.role == "tool" or message.role == "tool_results" or (message.tool_calls is defined and message.tool_calls is not none)) %} + {%- if (message["role"] == "user") != (ns.index % 2 == 0) %} + {{- raise_exception("After the optional system message, conversation roles must alternate user/assistant/user/assistant/...") }} + {%- endif %} + {%- set ns.index = ns.index + 1 %} + {%- endif %} +{%- endfor %} + +{{- bos_token }} +{%- for message in loop_messages %} + {%- if message["role"] == "user" %} + {%- if tools is not none and (message == user_messages[-1]) %} + {{- "[AVAILABLE_TOOLS] [" }} + {%- for tool in tools %} + {%- set tool = tool.function %} + {{- '{"type": "function", "function": {' }} + {%- for key, val in tool.items() if key != "return" %} + {%- if val is string %} + {{- '"' + key + '": "' + val + '"' }} + {%- else %} + {{- '"' + key + '": ' + val|tojson }} + {%- endif %} + {%- if not loop.last %} + {{- ", " }} + {%- endif %} + {%- endfor %} + {{- "}}" }} + {%- if not loop.last %} + {{- ", " }} + {%- else %} + {{- "]" }} + {%- endif %} + {%- endfor %} + {{- "[/AVAILABLE_TOOLS]" }} + {%- endif %} + {%- if loop.last and system_message is defined %} + {{- "[INST] " + system_message + "\n\n" + message["content"] + "[/INST]" }} + {%- else %} + {{- "[INST] " + message["content"] + "[/INST]" }} + {%- endif %} + {%- elif message.tool_calls is defined and message.tool_calls is not none %} + {{- "[TOOL_CALLS] [" }} + {%- for tool_call in message.tool_calls %} + {%- set out = tool_call.function|tojson %} + {{- out[:-1] }} + {%- if not tool_call.id is defined or tool_call.id|length != 9 %} + {{- raise_exception("Tool call IDs should be alphanumeric strings with length 9!") }} + {%- endif %} + {{- ', "id": "' + tool_call.id + '"}' }} + {%- if not loop.last %} + {{- ", " }} + {%- else %} + {{- "]" + eos_token }} + {%- endif %} + {%- endfor %} + {%- elif message["role"] == "assistant" %} + {{- " " + message["content"]|trim + eos_token}} + {%- elif message["role"] == "tool_results" or message["role"] == "tool" %} + {%- if message.content is defined and message.content.content is defined %} + {%- set content = message.content.content %} + {%- else %} + {%- set content = message.content %} + {%- endif %} + {{- '[TOOL_RESULTS] {"content": ' + content|string + ", " }} + {%- if not message.tool_call_id is defined or message.tool_call_id|length != 9 %} + {{- raise_exception("Tool call IDs should be alphanumeric strings with length 9!") }} + {%- endif %} + {{- '"call_id": "' + message.tool_call_id + '"}[/TOOL_RESULTS]' }} + {%- else %} + {{- raise_exception("Only user and assistant roles are supported, with the exception of an initial optional system message!") }} + {%- endif %} +{%- endfor %} diff --git a/crates/llm-runtime/tests/fixtures/chat_templates/qwen2.5.jinja b/crates/llm-runtime/tests/fixtures/chat_templates/qwen2.5.jinja new file mode 100644 index 000000000..bdf7919a9 --- /dev/null +++ b/crates/llm-runtime/tests/fixtures/chat_templates/qwen2.5.jinja @@ -0,0 +1,54 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0]['role'] == 'system' %} + {{- messages[0]['content'] }} + {%- else %} + {{- 'You are Qwen, created by Alibaba Cloud. You are a helpful assistant.' }} + {%- endif %} + {{- "\n\n# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0]['role'] == 'system' %} + {{- '<|im_start|>system\n' + messages[0]['content'] + '<|im_end|>\n' }} + {%- else %} + {{- '<|im_start|>system\nYou are Qwen, created by Alibaba Cloud. You are a helpful assistant.<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- for message in messages %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) or (message.role == "assistant" and not message.tool_calls) %} + {{- '<|im_start|>' + message.role + '\n' + message.content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {{- '<|im_start|>' + message.role }} + {%- if message.content %} + {{- '\n' + message.content }} + {%- endif %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {{- tool_call.arguments | tojson }} + {{- '}\n' }} + {%- endfor %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if (loop.index0 == 0) or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- message.content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} +{%- endif %} diff --git a/crates/llm-runtime/tests/fixtures/chat_templates/qwen3.5.jinja b/crates/llm-runtime/tests/fixtures/chat_templates/qwen3.5.jinja new file mode 100644 index 000000000..a585dec89 --- /dev/null +++ b/crates/llm-runtime/tests/fixtures/chat_templates/qwen3.5.jinja @@ -0,0 +1,154 @@ +{%- set image_count = namespace(value=0) %} +{%- set video_count = namespace(value=0) %} +{%- macro render_content(content, do_vision_count, is_system_content=false) %} + {%- if content is string %} + {{- content }} + {%- elif content is iterable and content is not mapping %} + {%- for item in content %} + {%- if 'image' in item or 'image_url' in item or item.type == 'image' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain images.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set image_count.value = image_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Picture ' ~ image_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|image_pad|><|vision_end|>' }} + {%- elif 'video' in item or item.type == 'video' %} + {%- if is_system_content %} + {{- raise_exception('System message cannot contain videos.') }} + {%- endif %} + {%- if do_vision_count %} + {%- set video_count.value = video_count.value + 1 %} + {%- endif %} + {%- if add_vision_id %} + {{- 'Video ' ~ video_count.value ~ ': ' }} + {%- endif %} + {{- '<|vision_start|><|video_pad|><|vision_end|>' }} + {%- elif 'text' in item %} + {{- item.text }} + {%- else %} + {{- raise_exception('Unexpected item type in content.') }} + {%- endif %} + {%- endfor %} + {%- elif content is none or content is undefined %} + {{- '' }} + {%- else %} + {{- raise_exception('Unexpected content type.') }} + {%- endif %} +{%- endmacro %} +{%- if not messages %} + {{- raise_exception('No messages provided.') }} +{%- endif %} +{%- if tools and tools is iterable and tools is not mapping %} + {{- '<|im_start|>system\n' }} + {{- "# Tools\n\nYou have access to the following functions:\n\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n" }} + {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\nThis is the value for the second parameter\nthat can span\nmultiple lines\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format: an inner block must be nested within XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n' }} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {%- if content %} + {{- '\n\n' + content }} + {%- endif %} + {%- endif %} + {{- '<|im_end|>\n' }} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- set content = render_content(messages[0].content, false, true)|trim %} + {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" %} + {%- set content = render_content(message.content, false)|trim %} + {%- if not(content.startswith('') and content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if ns.multi_step_tool %} + {{- raise_exception('No user query found in messages.') }} +{%- endif %} +{%- for message in messages %} + {%- set content = render_content(message.content, true)|trim %} + {%- if message.role == "system" %} + {%- if not loop.first %} + {{- raise_exception('System message must be at the beginning.') }} + {%- endif %} + {%- elif message.role == "user" %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- set reasoning_content = reasoning_content|trim %} + {%- if loop.index0 > ns.last_query_index %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content + '\n\n\n' + content }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %} + {%- for tool_call in message.tool_calls %} + {%- if tool_call.function is defined %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {%- if loop.first %} + {%- if content|trim %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n\n' }} + {%- endif %} + {%- else %} + {{- '\n\n\n' }} + {%- endif %} + {%- if tool_call.arguments is defined %} + {%- for args_name, args_value in tool_call.arguments|items %} + {{- '\n' }} + {%- set args_value = args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value | string %} + {{- args_value }} + {{- '\n\n' }} + {%- endfor %} + {%- endif %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.previtem and loop.previtem.role != "tool" %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if not loop.last and loop.nextitem.role != "tool" %} + {{- '<|im_end|>\n' }} + {%- elif loop.last %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- else %} + {{- raise_exception('Unexpected message role.') }} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- else %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/crates/llm-runtime/tests/fixtures/chat_templates/qwen3.jinja b/crates/llm-runtime/tests/fixtures/chat_templates/qwen3.jinja new file mode 100644 index 000000000..01be9b307 --- /dev/null +++ b/crates/llm-runtime/tests/fixtures/chat_templates/qwen3.jinja @@ -0,0 +1,89 @@ +{%- if tools %} + {{- '<|im_start|>system\n' }} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }} +{%- else %} + {%- if messages[0].role == 'system' %} + {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if (message.role == "user") or (message.role == "system" and not loop.first) %} + {{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- if loop.index0 > ns.last_query_index %} + {%- if loop.last or (not loop.last and reasoning_content) %} + {{- '<|im_start|>' + message.role + '\n\n' + reasoning_content.strip('\n') + '\n\n\n' + content.lstrip('\n') }} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- else %} + {{- '<|im_start|>' + message.role + '\n' + content }} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- if tool_call.function %} + {%- set tool_call = tool_call.function %} + {%- endif %} + {{- '\n{"name": "' }} + {{- tool_call.name }} + {{- '", "arguments": ' }} + {%- if tool_call.arguments is string %} + {{- tool_call.arguments }} + {%- else %} + {{- tool_call.arguments | tojson }} + {%- endif %} + {{- '}\n' }} + {%- endfor %} + {%- endif %} + {{- '<|im_end|>\n' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- '<|im_start|>user' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|im_end|>\n' }} + {%- endif %} + {%- endif %} +{%- endfor %} +{%- if add_generation_prompt %} + {{- '<|im_start|>assistant\n' }} + {%- if enable_thinking is defined and enable_thinking is false %} + {{- '\n\n\n\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file diff --git a/crates/llm-runtime/tests/openai_completions_caching_live.rs b/crates/llm-runtime/tests/openai_completions_caching_live.rs index a26916167..e39b2609d 100644 --- a/crates/llm-runtime/tests/openai_completions_caching_live.rs +++ b/crates/llm-runtime/tests/openai_completions_caching_live.rs @@ -1,8 +1,15 @@ //! Prompt caching on OpenAI Chat Completions, proven against the live API: //! with the session id as `prompt_cache_key`, the second request reports -//! most of the previous prompt as cached, and a tool round trip keeps the -//! hit. +//! most of the previous prompt as cached, a tool round trip keeps the hit, +//! and so does a refreshed catalog under layered instructions. +//! +//! `OPENAI_COMPLETIONS_BASE_URL` and `OPENAI_COMPLETIONS_PROVIDER_ID` point +//! the suite at a self-hosted server instead, for example vLLM started with +//! `--enable-prefix-caching --enable-prompt-tokens-details` and provider id +//! `vllm`. `OPENAI_COMPLETIONS_OUTPUT_LIMIT` gives a reasoning model room to +//! think, and `OPENAI_COMPLETIONS_EXTRA_BODY` adds server-specific fields. +use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; @@ -13,14 +20,18 @@ use harness::{ ToolChoice, ToolId, ToolSpec, TurnId, storage::{BlobStore, InMemoryBlobStore}, }; -use llm_runtime::{LlmGenerationAdapter, OpenAiCompletionsLlmAdapter, OpenAiCompletionsParams}; +use llm_runtime::{ + LlmGenerationAdapter, OpenAiCompletionsLlmAdapter, OpenAiCompletionsParams, ResolvedEndpoint, + ResolvedModelProvider, StaticModelProviders, +}; use serde_json::json; mod support; use support::{ caching::{MIN_CACHED_SHARE, assert_cached_share, long_instructions}, - openai_completions_live_client, openai_completions_live_model, openai_completions_params, + env_or_dotenv_var, openai_completions_live_client, openai_completions_live_model, + openai_completions_live_provider_id, openai_completions_params, retrying_openai_completions_client, }; @@ -55,13 +66,30 @@ fn entry( } fn instructions_entry(id: u64, content_ref: BlobRef) -> ContextEntry { + layer_entry(id, "instructions.000.live", content_ref) +} + +fn layer_entry(id: u64, key: &str, content_ref: BlobRef) -> ContextEntry { let mut entry = entry( id, ContextEntryKind::Instructions, ContextEntrySource::ContextEdit, content_ref, ); - entry.key = Some(ContextEntryKey::new("instructions.000.live")); + entry.key = Some(ContextEntryKey::new(key)); + entry +} + +fn catalog_entry(id: u64, content_ref: BlobRef, supersedes: Option) -> ContextEntry { + let mut entry = entry( + id, + ContextEntryKind::Catalog { + title: "Sub-agent catalog".to_owned(), + }, + ContextEntrySource::ContextEdit, + content_ref, + ); + entry.supersedes = supersedes.map(ContextEntryId::new); entry } @@ -108,7 +136,7 @@ fn intent_request(entries: Vec) -> LlmRequest { code_mode: None, model: ModelSelection { api_kind: ProviderApiKind::OpenAiCompletions, - provider_id: "openai".to_owned(), + provider_id: openai_completions_live_provider_id(), model: openai_completions_live_model(), }, request_fingerprint: "live-openai-completions-caching".to_owned(), @@ -120,7 +148,7 @@ fn intent_request(entries: Vec) -> LlmRequest { }, tools: Vec::new(), tool_choice: None, - output_limit: Some(256), + output_limit: Some(output_limit()), reasoning_effort: None, parallel_tool_use: None, processing_tier: None, @@ -128,11 +156,35 @@ fn intent_request(entries: Vec) -> LlmRequest { params: Some(openai_completions_params(&OpenAiCompletionsParams { store: Some(false), stream: Some(false), + extra: extra_body(), ..Default::default() })), } } +/// Reasoning models (Qwen 3.5 thinks first) need room beyond the answer: +/// `OPENAI_COMPLETIONS_OUTPUT_LIMIT` raises the default of 256. +fn output_limit() -> u32 { + env_or_dotenv_var("OPENAI_COMPLETIONS_OUTPUT_LIMIT") + .map(|limit| { + limit + .parse() + .expect("OPENAI_COMPLETIONS_OUTPUT_LIMIT is a number") + }) + .unwrap_or(256) +} + +/// Server-specific request fields from `OPENAI_COMPLETIONS_EXTRA_BODY`, a +/// JSON object, for example `{"chat_template_kwargs":{"enable_thinking":false}}` +/// for a Qwen model on vLLM. +fn extra_body() -> BTreeMap { + env_or_dotenv_var("OPENAI_COMPLETIONS_EXTRA_BODY") + .map(|body| { + serde_json::from_str(&body).expect("OPENAI_COMPLETIONS_EXTRA_BODY is a JSON object") + }) + .unwrap_or_default() +} + fn generation_request(turn_id: u64, request: LlmRequest) -> LlmGenerationRequest { LlmGenerationRequest { session_id: SessionId::new("session-live-openai-completions-caching"), @@ -143,10 +195,31 @@ fn generation_request(turn_id: u64, request: LlmRequest) -> LlmGenerationRequest } fn adapter(blobs: Arc) -> OpenAiCompletionsLlmAdapter { - OpenAiCompletionsLlmAdapter::new( + let adapter = OpenAiCompletionsLlmAdapter::new( retrying_openai_completions_client(openai_completions_live_client()), blobs, + ); + let provider_id = openai_completions_live_provider_id(); + if provider_id == "openai" { + return adapter; + } + // A custom provider, as a universe's model-provider record defines it: + // the server's base URL, Chat Completions, no stored credential. + let base_url = env_or_dotenv_var("OPENAI_COMPLETIONS_BASE_URL") + .expect("OPENAI_COMPLETIONS_BASE_URL is required with a custom provider id"); + let endpoint = ResolvedEndpoint::new( + &base_url, + &BTreeMap::new(), + ["openai:completions".to_owned()], ) + .expect("endpoint"); + adapter.with_provider_key_resolver(Arc::new(StaticModelProviders::new().with_provider( + provider_id, + ResolvedModelProvider { + auth: None, + endpoint: Some(endpoint), + }, + ))) } async fn generate( @@ -162,7 +235,13 @@ async fn generate( .generate(generation_request(turn_id, request)) .await .expect("generate"); - assert_eq!(execution.result.status, LlmGenerationStatus::Succeeded); + assert_eq!( + execution.result.status, + LlmGenerationStatus::Succeeded, + "finish {:?}, usage {:?}", + execution.result.facts.finish, + execution.result.facts.usage + ); let usage = execution .result .facts @@ -333,3 +412,77 @@ async fn openai_completions_caching_live_tool_round_trip_keeps_the_prefix_warm() prompt(&first), ); } + +/// The shape a real session sends: instructions in layers, a catalog before +/// the first message, and between runs a refreshed catalog at the tail. Chat +/// templates that accept only one leading system message (Qwen 3.5) reject +/// any other shape, and the refresh must not move the cached prefix. +#[tokio::test(flavor = "current_thread")] +#[ignore = "requires OPENAI_API_KEY (costs real money) or a self-hosted server"] +async fn openai_completions_caching_live_catalog_refresh_keeps_the_prefix_warm() { + let blobs = Arc::new(InMemoryBlobStore::new()); + let adapter = adapter(blobs.clone()); + let layers = vec![ + layer_entry( + 1, + "instructions.000.default", + text_blob(&blobs, &long_instructions()).await, + ), + layer_entry( + 2, + "instructions.050.profile", + text_blob(&blobs, "You are the release assistant of a small team.").await, + ), + layer_entry( + 3, + "instructions.110.environment", + text_blob(&blobs, "Commands run in /data/workspace.").await, + ), + ]; + let catalog = catalog_entry( + 4, + text_blob( + &blobs, + "- reviewer: reviews a diff\n- tester: runs the test suite", + ) + .await, + None, + ); + let first_ref = text_blob( + &blobs, + "Item 17 needs a status line. Reply in one sentence.", + ) + .await; + + let mut entries = layers; + entries.push(catalog); + entries.push(user_entry(5, first_ref)); + let (first, retained, _) = generate(&adapter, 1, intent_request(entries.clone())).await; + + entries.extend( + retained + .iter() + .enumerate() + .map(|(index, item)| retained_context_entry(6 + index as u64, item)), + ); + let next_id = entries.len() as u64 + 2; + entries.push(catalog_entry( + next_id, + text_blob( + &blobs, + "- reviewer: reviews a diff\n- tester: runs the test suite\n- writer: drafts release notes", + ) + .await, + Some(4), + )); + entries.push(user_entry( + next_id + 1, + text_blob(&blobs, "Now item 18. One sentence.").await, + )); + let second = generate_until_cached(&adapter, 2, intent_request(entries), prompt(&first)).await; + assert_cached_share( + "after a catalog refresh", + second.cached_input_tokens.unwrap_or(0), + prompt(&first), + ); +} diff --git a/crates/llm-runtime/tests/support/config.rs b/crates/llm-runtime/tests/support/config.rs index 2b790d2a4..19932fe5c 100644 --- a/crates/llm-runtime/tests/support/config.rs +++ b/crates/llm-runtime/tests/support/config.rs @@ -16,6 +16,13 @@ pub fn openai_completions_live_model() -> String { .unwrap_or_else(|_| "gpt-5.5".to_owned()) } +/// The provider id decides the request dialect: `openai` (the default) +/// sends `developer` messages; any other id, such as `vllm`, sends what a +/// self-hosted OpenAI-compatible server expects. +pub fn openai_completions_live_provider_id() -> String { + env_or_dotenv_var("OPENAI_COMPLETIONS_PROVIDER_ID").unwrap_or_else(|_| "openai".to_owned()) +} + pub fn openai_completions_live_client() -> CompletionsClient { CompletionsClient::new(openai_completions_config_with(env_or_dotenv_var)) .expect("OpenAI Completions client") diff --git a/crates/llm-runtime/tests/support/mod.rs b/crates/llm-runtime/tests/support/mod.rs index 1e6d65a7e..acb642816 100644 --- a/crates/llm-runtime/tests/support/mod.rs +++ b/crates/llm-runtime/tests/support/mod.rs @@ -3,7 +3,8 @@ mod config; pub use config::{ anthropic_messages_live_client, anthropic_messages_live_config, anthropic_messages_live_model, deepseek_completions_live_model, env_or_dotenv_var, openai_completions_live_client, - openai_completions_live_model, openai_responses_live_client, openai_responses_live_model, + openai_completions_live_model, openai_completions_live_provider_id, + openai_responses_live_client, openai_responses_live_model, }; use std::{sync::Arc, time::Duration};