mirror of
https://github.com/zed-industries/zed.git
synced 2026-12-01 21:10:37 +01:00
google_ai: Add long decode support (#67327)
Release Notes: - Added long decode support for Google BYOK models Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -206,6 +206,7 @@ pub fn into_google(
|
||||
allowed_function_names: None,
|
||||
},
|
||||
}),
|
||||
continuation_token: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -253,6 +254,7 @@ impl ThinkingConfig {
|
||||
|
||||
pub struct GoogleEventMapper {
|
||||
usage: UsageMetadata,
|
||||
previous_hops_usage: Option<UsageMetadata>,
|
||||
stop_emitted: bool,
|
||||
}
|
||||
|
||||
@@ -260,6 +262,7 @@ impl GoogleEventMapper {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
usage: UsageMetadata::default(),
|
||||
previous_hops_usage: None,
|
||||
stop_emitted: false,
|
||||
}
|
||||
}
|
||||
@@ -294,7 +297,10 @@ impl GoogleEventMapper {
|
||||
let mut events: Vec<_> = Vec::new();
|
||||
let mut wants_to_use_tool = false;
|
||||
let mut stop_reason = None;
|
||||
if let Some(usage_metadata) = event.usage_metadata {
|
||||
if let Some(mut usage_metadata) = event.usage_metadata {
|
||||
if let Some(previous_hops_usage) = &self.previous_hops_usage {
|
||||
add_previous_hops_usage(&mut usage_metadata, previous_hops_usage);
|
||||
}
|
||||
update_usage(&mut self.usage, &usage_metadata);
|
||||
// Streamed chunks carry an empty `usageMetadata` until the final one.
|
||||
// Reporting usage before the prompt count is known would show zero context.
|
||||
@@ -330,7 +336,10 @@ impl GoogleEventMapper {
|
||||
|
||||
if let Some(candidates) = event.candidates {
|
||||
for candidate in candidates {
|
||||
if let Some(finish_reason) = candidate.finish_reason.as_deref() {
|
||||
if candidate.finish_reason.as_deref() == Some("CONTINUATION") {
|
||||
// A long decode continues in another request, whose counts start over.
|
||||
self.previous_hops_usage = Some(self.usage.clone());
|
||||
} else if let Some(finish_reason) = candidate.finish_reason.as_deref() {
|
||||
stop_reason = Some(match finish_reason {
|
||||
"STOP" => StopReason::EndTurn,
|
||||
"MAX_TOKENS" => StopReason::MaxTokens,
|
||||
@@ -456,6 +465,19 @@ fn refusal_details(
|
||||
}
|
||||
}
|
||||
|
||||
/// Later long decode hops count everything generated so far as input again. That's already in
|
||||
/// the output counts, so the first hop's input counts are kept to avoid overstating the context.
|
||||
fn add_previous_hops_usage(usage: &mut UsageMetadata, previous_hops_usage: &UsageMetadata) {
|
||||
usage.prompt_token_count = previous_hops_usage.prompt_token_count;
|
||||
usage.cached_content_token_count = previous_hops_usage.cached_content_token_count;
|
||||
if let Some(candidates_token_count) = &mut usage.candidates_token_count {
|
||||
*candidates_token_count += previous_hops_usage.candidates_token_count.unwrap_or(0);
|
||||
}
|
||||
if let Some(thoughts_token_count) = &mut usage.thoughts_token_count {
|
||||
*thoughts_token_count += previous_hops_usage.thoughts_token_count.unwrap_or(0);
|
||||
}
|
||||
}
|
||||
|
||||
fn update_usage(usage: &mut UsageMetadata, new: &UsageMetadata) {
|
||||
if let Some(prompt_token_count) = new.prompt_token_count {
|
||||
usage.prompt_token_count = Some(prompt_token_count);
|
||||
@@ -804,6 +826,7 @@ mod tests {
|
||||
finish_message: None,
|
||||
safety_ratings: None,
|
||||
citation_metadata: None,
|
||||
continuation_token: None,
|
||||
}]),
|
||||
prompt_feedback: None,
|
||||
usage_metadata: None,
|
||||
@@ -901,6 +924,7 @@ mod tests {
|
||||
finish_message: None,
|
||||
safety_ratings: None,
|
||||
citation_metadata: None,
|
||||
continuation_token: None,
|
||||
}]),
|
||||
prompt_feedback: None,
|
||||
usage_metadata: None,
|
||||
@@ -980,6 +1004,7 @@ mod tests {
|
||||
finish_message: None,
|
||||
safety_ratings: None,
|
||||
citation_metadata: None,
|
||||
continuation_token: None,
|
||||
}]),
|
||||
prompt_feedback: None,
|
||||
usage_metadata: None,
|
||||
@@ -1021,6 +1046,7 @@ mod tests {
|
||||
finish_message: None,
|
||||
safety_ratings: None,
|
||||
citation_metadata: None,
|
||||
continuation_token: None,
|
||||
}]),
|
||||
prompt_feedback: None,
|
||||
usage_metadata: None,
|
||||
@@ -1058,6 +1084,7 @@ mod tests {
|
||||
finish_message: None,
|
||||
safety_ratings: None,
|
||||
citation_metadata: None,
|
||||
continuation_token: None,
|
||||
}]),
|
||||
prompt_feedback: None,
|
||||
usage_metadata: None,
|
||||
@@ -1070,4 +1097,54 @@ mod tests {
|
||||
panic!("Expected ToolUse event");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_decode_usage_counts_each_generated_token_once() {
|
||||
// Each hop counts output from zero but re-counts earlier output as prompt input.
|
||||
let hops = [
|
||||
(10, 0, 4, 20, "CONTINUATION"),
|
||||
(34, 30, 6, 14, "CONTINUATION"),
|
||||
(54, 50, 5, 1, "STOP"),
|
||||
];
|
||||
let mut mapper = GoogleEventMapper::new();
|
||||
let events = hops
|
||||
.into_iter()
|
||||
.flat_map(|(prompt, cached, candidates, thoughts, finish_reason)| {
|
||||
mapper.map_event(
|
||||
serde_json::from_value(json!({
|
||||
"candidates": [{
|
||||
"content": {"role": "model", "parts": []},
|
||||
"finishReason": finish_reason
|
||||
}],
|
||||
"usageMetadata": {
|
||||
"promptTokenCount": prompt,
|
||||
"cachedContentTokenCount": cached,
|
||||
"candidatesTokenCount": candidates,
|
||||
"thoughtsTokenCount": thoughts
|
||||
}
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
})
|
||||
.map(Result::unwrap)
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let usage = |output_tokens| {
|
||||
LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
|
||||
input_tokens: 10,
|
||||
output_tokens,
|
||||
cache_read_input_tokens: 0,
|
||||
cache_creation_input_tokens: 0,
|
||||
})
|
||||
};
|
||||
assert_eq!(
|
||||
events,
|
||||
[
|
||||
usage(24),
|
||||
usage(44),
|
||||
usage(50),
|
||||
LanguageModelCompletionEvent::Stop(StopReason::EndTurn),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::mem;
|
||||
use std::{mem, sync::Arc};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use futures::{AsyncBufReadExt, AsyncReadExt, StreamExt, io::BufReader, stream::BoxStream};
|
||||
@@ -65,6 +65,17 @@ pub(crate) fn uses_sibling_function_response_media(model_id: &str) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// Models that can keep generating past one response's output limit when the client resends the
|
||||
/// request with the `continuationToken` the previous response ended with.
|
||||
///
|
||||
/// See <https://ai.google.dev/gemini-api/docs/long-decode>.
|
||||
pub fn supports_long_decode(model_id: &str) -> bool {
|
||||
matches!(
|
||||
model_id,
|
||||
"gemini-4-carbon" | "gemini-4-argon" | "gemini-4-neon" | "gemini-4-hydrogen"
|
||||
)
|
||||
}
|
||||
|
||||
/// Level-based models that accept `MINIMAL`; the others reject it and start at `LOW`.
|
||||
fn supports_minimal_thinking(model_id: &str) -> bool {
|
||||
matches!(
|
||||
@@ -204,7 +215,7 @@ pub async fn list_models(
|
||||
}
|
||||
|
||||
pub async fn stream_generate_content(
|
||||
client: &dyn HttpClient,
|
||||
client: Arc<dyn HttpClient>,
|
||||
api_url: &str,
|
||||
api_key: &str,
|
||||
mut request: GenerateContentRequest,
|
||||
@@ -222,12 +233,40 @@ pub async fn stream_generate_content(
|
||||
let uri =
|
||||
format!("{api_url}/v1beta/models/{model_id}:streamGenerateContent?alt=sse&key={api_key}",);
|
||||
|
||||
let first_hop = stream_hop(client.as_ref(), &uri, api_url, &request, extra_headers).await?;
|
||||
if !supports_long_decode(&model_id) {
|
||||
return Ok(first_hop);
|
||||
}
|
||||
|
||||
Ok(LongDecodeRequest {
|
||||
client,
|
||||
uri,
|
||||
api_url: api_url.to_string(),
|
||||
extra_headers: extra_headers.clone(),
|
||||
request,
|
||||
hop: first_hop,
|
||||
continuation_token: None,
|
||||
continues: false,
|
||||
}
|
||||
.into_stream())
|
||||
}
|
||||
|
||||
type ResponseStream =
|
||||
BoxStream<'static, Result<GenerateContentResponse, LanguageModelCompletionError>>;
|
||||
|
||||
async fn stream_hop(
|
||||
client: &dyn HttpClient,
|
||||
uri: &str,
|
||||
api_url: &str,
|
||||
request: &GenerateContentRequest,
|
||||
extra_headers: &CustomHeaders,
|
||||
) -> Result<ResponseStream, LanguageModelCompletionError> {
|
||||
let request = HttpRequest::builder()
|
||||
.method(Method::POST)
|
||||
.uri(uri)
|
||||
.header("Content-Type", "application/json")
|
||||
.extra_headers(extra_headers)
|
||||
.body(AsyncBody::from(serde_json::to_string(&request).map_err(
|
||||
.body(AsyncBody::from(serde_json::to_string(request).map_err(
|
||||
|error| LanguageModelCompletionError::SerializeRequest {
|
||||
provider: GOOGLE_PROVIDER_NAME,
|
||||
error,
|
||||
@@ -299,6 +338,71 @@ pub async fn stream_generate_content(
|
||||
}
|
||||
}
|
||||
|
||||
/// Joins the hops of a long decode into one stream that ends when the last hop does.
|
||||
struct LongDecodeRequest {
|
||||
client: Arc<dyn HttpClient>,
|
||||
uri: String,
|
||||
api_url: String,
|
||||
extra_headers: CustomHeaders,
|
||||
request: GenerateContentRequest,
|
||||
hop: ResponseStream,
|
||||
continuation_token: Option<String>,
|
||||
continues: bool,
|
||||
}
|
||||
|
||||
impl LongDecodeRequest {
|
||||
fn into_stream(self) -> ResponseStream {
|
||||
futures::stream::unfold(Some(self), |state| async move {
|
||||
let mut state = state?;
|
||||
let response = state.next_response().await?;
|
||||
let state = response.is_ok().then_some(state);
|
||||
Some((response, state))
|
||||
})
|
||||
.boxed()
|
||||
}
|
||||
|
||||
async fn next_response(
|
||||
&mut self,
|
||||
) -> Option<Result<GenerateContentResponse, LanguageModelCompletionError>> {
|
||||
loop {
|
||||
match self.hop.next().await {
|
||||
Some(Ok(mut response)) => {
|
||||
for candidate in response.candidates.iter_mut().flatten() {
|
||||
// Streams also carry checkpoint tokens before the hop's last chunk.
|
||||
if let Some(continuation_token) = candidate.continuation_token.take() {
|
||||
self.continuation_token = Some(continuation_token);
|
||||
}
|
||||
if candidate.finish_reason.as_deref() == Some("CONTINUATION") {
|
||||
self.continues = true;
|
||||
}
|
||||
}
|
||||
return Some(Ok(response));
|
||||
}
|
||||
Some(Err(error)) => return Some(Err(error)),
|
||||
None => {}
|
||||
}
|
||||
|
||||
if !mem::take(&mut self.continues) {
|
||||
return None;
|
||||
}
|
||||
let continuation_token = self.continuation_token.take()?;
|
||||
self.request.continuation_token = Some(continuation_token);
|
||||
match stream_hop(
|
||||
self.client.as_ref(),
|
||||
&self.uri,
|
||||
&self.api_url,
|
||||
&self.request,
|
||||
&self.extra_headers,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(hop) => self.hop = hop,
|
||||
Err(error) => return Some(Err(error)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn completion_error_from_response(
|
||||
status: StatusCode,
|
||||
headers: &HeaderMap,
|
||||
@@ -504,6 +608,9 @@ pub struct GenerateContentRequest {
|
||||
pub tools: Option<Vec<Tool>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tool_config: Option<ToolConfig>,
|
||||
/// Resumes a long decode from where a previous response stopped.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub continuation_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -533,6 +640,8 @@ pub struct GenerateContentCandidate {
|
||||
pub safety_ratings: Option<Vec<SafetyRating>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub citation_metadata: Option<CitationMetadata>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub continuation_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -646,7 +755,7 @@ pub struct PromptFeedback {
|
||||
pub block_reason_message: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Default)]
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UsageMetadata {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -1046,7 +1155,7 @@ mod tests {
|
||||
}))
|
||||
.unwrap();
|
||||
let responses = stream_generate_content(
|
||||
client.as_ref(),
|
||||
client,
|
||||
API_URL,
|
||||
"test-key",
|
||||
request,
|
||||
@@ -1065,6 +1174,93 @@ mod tests {
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_decode_continues_until_a_hop_finishes() {
|
||||
let request_bodies: Arc<std::sync::Mutex<Vec<serde_json::Value>>> = Arc::default();
|
||||
let client = FakeHttpClient::create({
|
||||
let request_bodies = request_bodies.clone();
|
||||
move |mut request| {
|
||||
let request_bodies = request_bodies.clone();
|
||||
async move {
|
||||
let mut body = String::new();
|
||||
request.body_mut().read_to_string(&mut body).await?;
|
||||
let body: serde_json::Value = serde_json::from_str(&body)?;
|
||||
let chunks = if body.get("continuationToken").is_none() {
|
||||
[
|
||||
json!({
|
||||
"candidates": [{
|
||||
"content": {"role": "model", "parts": [{"text": "Part one. "}]},
|
||||
"continuationToken": "checkpoint"
|
||||
}]
|
||||
}),
|
||||
json!({
|
||||
"candidates": [{
|
||||
"content": {"role": "model", "parts": []},
|
||||
"finishReason": "CONTINUATION",
|
||||
"continuationToken": "hop-1"
|
||||
}]
|
||||
}),
|
||||
]
|
||||
.to_vec()
|
||||
} else {
|
||||
vec![json!({
|
||||
"candidates": [{
|
||||
"content": {"role": "model", "parts": [{"text": "Part two."}]},
|
||||
"finishReason": "STOP"
|
||||
}]
|
||||
})]
|
||||
};
|
||||
request_bodies.lock().unwrap().push(body);
|
||||
let sse = chunks
|
||||
.iter()
|
||||
.map(|chunk| format!("data: {chunk}\n\n"))
|
||||
.collect::<String>();
|
||||
Ok(Response::builder().body(AsyncBody::from(sse))?)
|
||||
}
|
||||
}
|
||||
});
|
||||
let request = serde_json::from_value(json!({
|
||||
"model": "models/gemini-4-argon",
|
||||
"contents": [{"role": "user", "parts": [{"text": "Prove it"}]}],
|
||||
"generationConfig": {"maxOutputTokens": 1_048_576}
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
let events = futures::executor::block_on(async {
|
||||
let responses = stream_generate_content(
|
||||
client,
|
||||
API_URL,
|
||||
"test-key",
|
||||
request,
|
||||
&CustomHeaders::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
GoogleEventMapper::new()
|
||||
.map_stream(responses)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
events,
|
||||
[
|
||||
LanguageModelCompletionEvent::Text("Part one. ".into()),
|
||||
LanguageModelCompletionEvent::Text("Part two.".into()),
|
||||
LanguageModelCompletionEvent::Stop(language_model_core::StopReason::EndTurn),
|
||||
]
|
||||
);
|
||||
let request_bodies = request_bodies.lock().unwrap();
|
||||
assert_eq!(request_bodies.len(), 2);
|
||||
assert_eq!(request_bodies[1]["continuationToken"], "hop-1");
|
||||
assert_eq!(request_bodies[0]["contents"], request_bodies[1]["contents"]);
|
||||
assert_eq!(
|
||||
request_bodies[0]["generationConfig"],
|
||||
request_bodies[1]["generationConfig"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_lowest_thinking_level_per_model() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -270,7 +270,7 @@ impl GoogleLanguageModelProvider {
|
||||
});
|
||||
};
|
||||
let request = google_ai::stream_generate_content(
|
||||
http_client.as_ref(),
|
||||
http_client,
|
||||
&api_url,
|
||||
&api_key,
|
||||
request,
|
||||
@@ -374,7 +374,12 @@ impl LanguageModelClient for GoogleLanguageModelProvider {
|
||||
};
|
||||
let request_limiter = self.request_limiters.for_model(&model.id);
|
||||
let mut request = request;
|
||||
if request.max_output_tokens.is_some() {
|
||||
if google_ai::supports_long_decode(&config.id) {
|
||||
// Long decode only continues past one response's output limit when the budget allows
|
||||
// it. Google accepts the whole context window as that budget.
|
||||
request.max_output_tokens =
|
||||
request.effective_max_output_tokens(Some(config.max_input_tokens));
|
||||
} else if request.max_output_tokens.is_some() {
|
||||
request.max_output_tokens =
|
||||
request.effective_max_output_tokens(config.max_output_tokens);
|
||||
}
|
||||
@@ -460,10 +465,13 @@ mod tests {
|
||||
#[gpui::test]
|
||||
async fn catalog_models_drop_xhigh_effort_unless_supported(cx: &mut TestAppContext) {
|
||||
let thinking_configs: Arc<Mutex<Vec<(String, serde_json::Value)>>> = Arc::default();
|
||||
let max_output_tokens: Arc<Mutex<Vec<serde_json::Value>>> = Arc::default();
|
||||
let http_client = FakeHttpClient::create({
|
||||
let thinking_configs = thinking_configs.clone();
|
||||
let max_output_tokens = max_output_tokens.clone();
|
||||
move |mut request| {
|
||||
let thinking_configs = thinking_configs.clone();
|
||||
let max_output_tokens = max_output_tokens.clone();
|
||||
async move {
|
||||
if request.method() == Method::GET {
|
||||
let models = ["gemini-4-hydrogen", "gemini-4-argon"].map(|id| {
|
||||
@@ -489,6 +497,9 @@ mod tests {
|
||||
request.uri().path().to_string(),
|
||||
body["generationConfig"]["thinkingConfig"].clone(),
|
||||
));
|
||||
max_output_tokens
|
||||
.lock()
|
||||
.push(body["generationConfig"]["maxOutputTokens"].clone());
|
||||
Ok(Response::builder().status(200).body(AsyncBody::from(
|
||||
"data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}\n\n",
|
||||
))?)
|
||||
@@ -557,5 +568,9 @@ mod tests {
|
||||
),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
*max_output_tokens.lock(),
|
||||
[json!(1_048_576), json!(1_048_576)]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user