open_router.rs

   1use anyhow::{Result, anyhow};
   2use collections::HashMap;
   3use futures::{FutureExt, Stream, StreamExt, future::BoxFuture};
   4use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task};
   5use http_client::HttpClient;
   6use language_model::{
   7    ApiKeyState, AuthenticateError, EnvVar, IconOrSvg, LanguageModel, LanguageModelCompletionError,
   8    LanguageModelCompletionEvent, LanguageModelId, LanguageModelName, LanguageModelProvider,
   9    LanguageModelProviderId, LanguageModelProviderName, LanguageModelProviderState,
  10    LanguageModelRequest, LanguageModelToolChoice, LanguageModelToolResultContent,
  11    LanguageModelToolSchemaFormat, LanguageModelToolUse, MessageContent, RateLimiter, Role,
  12    StopReason, TokenUsage, env_var,
  13};
  14use open_router::{
  15    Model, ModelMode as OpenRouterModelMode, OPEN_ROUTER_API_URL, ResponseStreamEvent, list_models,
  16};
  17use settings::{OpenRouterAvailableModel as AvailableModel, Settings, SettingsStore};
  18use std::pin::Pin;
  19use std::str::FromStr as _;
  20use std::sync::{Arc, LazyLock};
  21use ui::{ButtonLink, ConfiguredApiCard, List, ListBulletItem, prelude::*};
  22use ui_input::InputField;
  23use util::ResultExt;
  24
  25const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("openrouter");
  26const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("OpenRouter");
  27
  28const API_KEY_ENV_VAR_NAME: &str = "OPENROUTER_API_KEY";
  29static API_KEY_ENV_VAR: LazyLock<EnvVar> = env_var!(API_KEY_ENV_VAR_NAME);
  30
  31#[derive(Default, Clone, Debug, PartialEq)]
  32pub struct OpenRouterSettings {
  33    pub api_url: String,
  34    pub available_models: Vec<AvailableModel>,
  35}
  36
  37pub struct OpenRouterLanguageModelProvider {
  38    http_client: Arc<dyn HttpClient>,
  39    state: Entity<State>,
  40}
  41
  42pub struct State {
  43    api_key_state: ApiKeyState,
  44    http_client: Arc<dyn HttpClient>,
  45    available_models: Vec<open_router::Model>,
  46    fetch_models_task: Option<Task<Result<(), LanguageModelCompletionError>>>,
  47}
  48
  49impl State {
  50    fn is_authenticated(&self) -> bool {
  51        self.api_key_state.has_key()
  52    }
  53
  54    fn set_api_key(&mut self, api_key: Option<String>, cx: &mut Context<Self>) -> Task<Result<()>> {
  55        let api_url = OpenRouterLanguageModelProvider::api_url(cx);
  56        self.api_key_state
  57            .store(api_url, api_key, |this| &mut this.api_key_state, cx)
  58    }
  59
  60    fn authenticate(&mut self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
  61        let api_url = OpenRouterLanguageModelProvider::api_url(cx);
  62        let task = self
  63            .api_key_state
  64            .load_if_needed(api_url, |this| &mut this.api_key_state, cx);
  65
  66        cx.spawn(async move |this, cx| {
  67            let result = task.await;
  68            this.update(cx, |this, cx| this.restart_fetch_models_task(cx))
  69                .ok();
  70            result
  71        })
  72    }
  73
  74    fn fetch_models(
  75        &mut self,
  76        cx: &mut Context<Self>,
  77    ) -> Task<Result<(), LanguageModelCompletionError>> {
  78        let http_client = self.http_client.clone();
  79        let api_url = OpenRouterLanguageModelProvider::api_url(cx);
  80        let Some(api_key) = self.api_key_state.key(&api_url) else {
  81            return Task::ready(Err(LanguageModelCompletionError::NoApiKey {
  82                provider: PROVIDER_NAME,
  83            }));
  84        };
  85        cx.spawn(async move |this, cx| {
  86            let models = list_models(http_client.as_ref(), &api_url, &api_key)
  87                .await
  88                .map_err(|e| {
  89                    LanguageModelCompletionError::Other(anyhow::anyhow!(
  90                        "OpenRouter error: {:?}",
  91                        e
  92                    ))
  93                })?;
  94
  95            this.update(cx, |this, cx| {
  96                this.available_models = models;
  97                cx.notify();
  98            })
  99            .map_err(|e| LanguageModelCompletionError::Other(e))?;
 100
 101            Ok(())
 102        })
 103    }
 104
 105    fn restart_fetch_models_task(&mut self, cx: &mut Context<Self>) {
 106        if self.is_authenticated() {
 107            let task = self.fetch_models(cx);
 108            self.fetch_models_task.replace(task);
 109        } else {
 110            self.available_models = Vec::new();
 111        }
 112    }
 113}
 114
 115impl OpenRouterLanguageModelProvider {
 116    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
 117        let state = cx.new(|cx| {
 118            cx.observe_global::<SettingsStore>({
 119                let mut last_settings = OpenRouterLanguageModelProvider::settings(cx).clone();
 120                move |this: &mut State, cx| {
 121                    let current_settings = OpenRouterLanguageModelProvider::settings(cx);
 122                    let settings_changed = current_settings != &last_settings;
 123                    if settings_changed {
 124                        last_settings = current_settings.clone();
 125                        this.authenticate(cx).detach();
 126                        cx.notify();
 127                    }
 128                }
 129            })
 130            .detach();
 131            State {
 132                api_key_state: ApiKeyState::new(Self::api_url(cx), (*API_KEY_ENV_VAR).clone()),
 133                http_client: http_client.clone(),
 134                available_models: Vec::new(),
 135                fetch_models_task: None,
 136            }
 137        });
 138
 139        Self { http_client, state }
 140    }
 141
 142    fn settings(cx: &App) -> &OpenRouterSettings {
 143        &crate::AllLanguageModelSettings::get_global(cx).open_router
 144    }
 145
 146    fn api_url(cx: &App) -> SharedString {
 147        let api_url = &Self::settings(cx).api_url;
 148        if api_url.is_empty() {
 149            OPEN_ROUTER_API_URL.into()
 150        } else {
 151            SharedString::new(api_url.as_str())
 152        }
 153    }
 154
 155    fn create_language_model(&self, model: open_router::Model) -> Arc<dyn LanguageModel> {
 156        Arc::new(OpenRouterLanguageModel {
 157            id: LanguageModelId::from(model.id().to_string()),
 158            model,
 159            state: self.state.clone(),
 160            http_client: self.http_client.clone(),
 161            request_limiter: RateLimiter::new(4),
 162        })
 163    }
 164}
 165
 166impl LanguageModelProviderState for OpenRouterLanguageModelProvider {
 167    type ObservableEntity = State;
 168
 169    fn observable_entity(&self) -> Option<Entity<Self::ObservableEntity>> {
 170        Some(self.state.clone())
 171    }
 172}
 173
 174impl LanguageModelProvider for OpenRouterLanguageModelProvider {
 175    fn id(&self) -> LanguageModelProviderId {
 176        PROVIDER_ID
 177    }
 178
 179    fn name(&self) -> LanguageModelProviderName {
 180        PROVIDER_NAME
 181    }
 182
 183    fn icon(&self) -> IconOrSvg {
 184        IconOrSvg::Icon(IconName::AiOpenRouter)
 185    }
 186
 187    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
 188        Some(self.create_language_model(open_router::Model::default()))
 189    }
 190
 191    fn default_fast_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
 192        Some(self.create_language_model(open_router::Model::default_fast()))
 193    }
 194
 195    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
 196        let mut models_from_api = self.state.read(cx).available_models.clone();
 197        let mut settings_models = Vec::new();
 198
 199        for model in &Self::settings(cx).available_models {
 200            settings_models.push(open_router::Model {
 201                name: model.name.clone(),
 202                display_name: model.display_name.clone(),
 203                max_tokens: model.max_tokens,
 204                supports_tools: model.supports_tools,
 205                supports_images: model.supports_images,
 206                mode: model.mode.unwrap_or_default(),
 207                provider: model.provider.clone(),
 208            });
 209        }
 210
 211        for settings_model in &settings_models {
 212            if let Some(pos) = models_from_api
 213                .iter()
 214                .position(|m| m.name == settings_model.name)
 215            {
 216                models_from_api[pos] = settings_model.clone();
 217            } else {
 218                models_from_api.push(settings_model.clone());
 219            }
 220        }
 221
 222        models_from_api
 223            .into_iter()
 224            .map(|model| self.create_language_model(model))
 225            .collect()
 226    }
 227
 228    fn is_authenticated(&self, cx: &App) -> bool {
 229        self.state.read(cx).is_authenticated()
 230    }
 231
 232    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
 233        self.state.update(cx, |state, cx| state.authenticate(cx))
 234    }
 235
 236    fn configuration_view(
 237        &self,
 238        _target_agent: language_model::ConfigurationViewTargetAgent,
 239        window: &mut Window,
 240        cx: &mut App,
 241    ) -> AnyView {
 242        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
 243            .into()
 244    }
 245
 246    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
 247        self.state
 248            .update(cx, |state, cx| state.set_api_key(None, cx))
 249    }
 250}
 251
 252pub struct OpenRouterLanguageModel {
 253    id: LanguageModelId,
 254    model: open_router::Model,
 255    state: Entity<State>,
 256    http_client: Arc<dyn HttpClient>,
 257    request_limiter: RateLimiter,
 258}
 259
 260impl OpenRouterLanguageModel {
 261    fn stream_completion(
 262        &self,
 263        request: open_router::Request,
 264        cx: &AsyncApp,
 265    ) -> BoxFuture<
 266        'static,
 267        Result<
 268            futures::stream::BoxStream<
 269                'static,
 270                Result<ResponseStreamEvent, open_router::OpenRouterError>,
 271            >,
 272            LanguageModelCompletionError,
 273        >,
 274    > {
 275        let http_client = self.http_client.clone();
 276        let (api_key, api_url) = self.state.read_with(cx, |state, cx| {
 277            let api_url = OpenRouterLanguageModelProvider::api_url(cx);
 278            (state.api_key_state.key(&api_url), api_url)
 279        });
 280
 281        async move {
 282            let Some(api_key) = api_key else {
 283                return Err(LanguageModelCompletionError::NoApiKey {
 284                    provider: PROVIDER_NAME,
 285                });
 286            };
 287            let request =
 288                open_router::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
 289            request.await.map_err(Into::into)
 290        }
 291        .boxed()
 292    }
 293}
 294
 295impl LanguageModel for OpenRouterLanguageModel {
 296    fn id(&self) -> LanguageModelId {
 297        self.id.clone()
 298    }
 299
 300    fn name(&self) -> LanguageModelName {
 301        LanguageModelName::from(self.model.display_name().to_string())
 302    }
 303
 304    fn provider_id(&self) -> LanguageModelProviderId {
 305        PROVIDER_ID
 306    }
 307
 308    fn provider_name(&self) -> LanguageModelProviderName {
 309        PROVIDER_NAME
 310    }
 311
 312    fn supports_tools(&self) -> bool {
 313        self.model.supports_tool_calls()
 314    }
 315
 316    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
 317        let model_id = self.model.id().trim().to_lowercase();
 318        if model_id.contains("gemini") || model_id.contains("grok") {
 319            LanguageModelToolSchemaFormat::JsonSchemaSubset
 320        } else {
 321            LanguageModelToolSchemaFormat::JsonSchema
 322        }
 323    }
 324
 325    fn telemetry_id(&self) -> String {
 326        format!("openrouter/{}", self.model.id())
 327    }
 328
 329    fn max_token_count(&self) -> u64 {
 330        self.model.max_token_count()
 331    }
 332
 333    fn max_output_tokens(&self) -> Option<u64> {
 334        self.model.max_output_tokens()
 335    }
 336
 337    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
 338        match choice {
 339            LanguageModelToolChoice::Auto => true,
 340            LanguageModelToolChoice::Any => true,
 341            LanguageModelToolChoice::None => true,
 342        }
 343    }
 344
 345    fn supports_images(&self) -> bool {
 346        self.model.supports_images.unwrap_or(false)
 347    }
 348
 349    fn count_tokens(
 350        &self,
 351        request: LanguageModelRequest,
 352        cx: &App,
 353    ) -> BoxFuture<'static, Result<u64>> {
 354        count_open_router_tokens(request, self.model.clone(), cx)
 355    }
 356
 357    fn stream_completion(
 358        &self,
 359        request: LanguageModelRequest,
 360        cx: &AsyncApp,
 361    ) -> BoxFuture<
 362        'static,
 363        Result<
 364            futures::stream::BoxStream<
 365                'static,
 366                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
 367            >,
 368            LanguageModelCompletionError,
 369        >,
 370    > {
 371        let openrouter_request = into_open_router(request, &self.model, self.max_output_tokens());
 372        let request = self.stream_completion(openrouter_request, cx);
 373        let future = self.request_limiter.stream(async move {
 374            let response = request.await?;
 375            Ok(OpenRouterEventMapper::new().map_stream(response))
 376        });
 377        async move { Ok(future.await?.boxed()) }.boxed()
 378    }
 379}
 380
 381pub fn into_open_router(
 382    request: LanguageModelRequest,
 383    model: &Model,
 384    max_output_tokens: Option<u64>,
 385) -> open_router::Request {
 386    // Anthropic models via OpenRouter don't accept reasoning_details being echoed back
 387    // in requests - it's an output-only field for them. However, Gemini models require
 388    // the thought signatures to be echoed back for proper reasoning chain continuity.
 389    // Note: OpenRouter's model API provides an `architecture.tokenizer` field (e.g. "Claude",
 390    // "Gemini") which could replace this ID prefix check, but since this is the only place
 391    // we need this distinction, we're just using this less invasive check instead.
 392    // If we ever have a more formal distionction between the models in the future,
 393    // we should revise this to use that instead.
 394    let is_anthropic_model = model.id().starts_with("anthropic/");
 395
 396    let mut messages = Vec::new();
 397    for message in request.messages {
 398        let reasoning_details_for_message = if is_anthropic_model {
 399            None
 400        } else {
 401            message.reasoning_details.clone()
 402        };
 403
 404        for content in message.content {
 405            match content {
 406                MessageContent::Text(text) => add_message_content_part(
 407                    open_router::MessagePart::Text { text },
 408                    message.role,
 409                    &mut messages,
 410                    reasoning_details_for_message.clone(),
 411                ),
 412                MessageContent::Thinking { .. } => {}
 413                MessageContent::RedactedThinking(_) => {}
 414                MessageContent::Image(image) => {
 415                    add_message_content_part(
 416                        open_router::MessagePart::Image {
 417                            image_url: image.to_base64_url(),
 418                        },
 419                        message.role,
 420                        &mut messages,
 421                        reasoning_details_for_message.clone(),
 422                    );
 423                }
 424                MessageContent::ToolUse(tool_use) => {
 425                    let tool_call = open_router::ToolCall {
 426                        id: tool_use.id.to_string(),
 427                        content: open_router::ToolCallContent::Function {
 428                            function: open_router::FunctionContent {
 429                                name: tool_use.name.to_string(),
 430                                arguments: serde_json::to_string(&tool_use.input)
 431                                    .unwrap_or_default(),
 432                                thought_signature: tool_use.thought_signature.clone(),
 433                            },
 434                        },
 435                    };
 436
 437                    if let Some(open_router::RequestMessage::Assistant { tool_calls, .. }) =
 438                        messages.last_mut()
 439                    {
 440                        tool_calls.push(tool_call);
 441                    } else {
 442                        messages.push(open_router::RequestMessage::Assistant {
 443                            content: None,
 444                            tool_calls: vec![tool_call],
 445                            reasoning_details: reasoning_details_for_message.clone(),
 446                        });
 447                    }
 448                }
 449                MessageContent::ToolResult(tool_result) => {
 450                    let content = match &tool_result.content {
 451                        LanguageModelToolResultContent::Text(text) => {
 452                            vec![open_router::MessagePart::Text {
 453                                text: text.to_string(),
 454                            }]
 455                        }
 456                        LanguageModelToolResultContent::Image(image) => {
 457                            vec![open_router::MessagePart::Image {
 458                                image_url: image.to_base64_url(),
 459                            }]
 460                        }
 461                    };
 462
 463                    messages.push(open_router::RequestMessage::Tool {
 464                        content: content.into(),
 465                        tool_call_id: tool_result.tool_use_id.to_string(),
 466                    });
 467                }
 468            }
 469        }
 470    }
 471
 472    open_router::Request {
 473        model: model.id().into(),
 474        messages,
 475        stream: true,
 476        stop: request.stop,
 477        temperature: request.temperature.unwrap_or(0.4),
 478        max_tokens: max_output_tokens,
 479        parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
 480            Some(false)
 481        } else {
 482            None
 483        },
 484        usage: open_router::RequestUsage { include: true },
 485        reasoning: if request.thinking_allowed
 486            && let OpenRouterModelMode::Thinking { budget_tokens } = model.mode
 487        {
 488            Some(open_router::Reasoning {
 489                effort: None,
 490                max_tokens: budget_tokens,
 491                exclude: Some(false),
 492                enabled: Some(true),
 493            })
 494        } else {
 495            None
 496        },
 497        tools: request
 498            .tools
 499            .into_iter()
 500            .map(|tool| open_router::ToolDefinition::Function {
 501                function: open_router::FunctionDefinition {
 502                    name: tool.name,
 503                    description: Some(tool.description),
 504                    parameters: Some(tool.input_schema),
 505                },
 506            })
 507            .collect(),
 508        tool_choice: request.tool_choice.map(|choice| match choice {
 509            LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
 510            LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
 511            LanguageModelToolChoice::None => open_router::ToolChoice::None,
 512        }),
 513        provider: model.provider.clone(),
 514    }
 515}
 516
 517fn add_message_content_part(
 518    new_part: open_router::MessagePart,
 519    role: Role,
 520    messages: &mut Vec<open_router::RequestMessage>,
 521    reasoning_details: Option<serde_json::Value>,
 522) {
 523    match (role, messages.last_mut()) {
 524        (Role::User, Some(open_router::RequestMessage::User { content }))
 525        | (Role::System, Some(open_router::RequestMessage::System { content })) => {
 526            content.push_part(new_part);
 527        }
 528        (
 529            Role::Assistant,
 530            Some(open_router::RequestMessage::Assistant {
 531                content: Some(content),
 532                ..
 533            }),
 534        ) => {
 535            content.push_part(new_part);
 536        }
 537        _ => {
 538            messages.push(match role {
 539                Role::User => open_router::RequestMessage::User {
 540                    content: open_router::MessageContent::from(vec![new_part]),
 541                },
 542                Role::Assistant => open_router::RequestMessage::Assistant {
 543                    content: Some(open_router::MessageContent::from(vec![new_part])),
 544                    tool_calls: Vec::new(),
 545                    reasoning_details,
 546                },
 547                Role::System => open_router::RequestMessage::System {
 548                    content: open_router::MessageContent::from(vec![new_part]),
 549                },
 550            });
 551        }
 552    }
 553}
 554
 555pub struct OpenRouterEventMapper {
 556    tool_calls_by_index: HashMap<usize, RawToolCall>,
 557    reasoning_details: Option<serde_json::Value>,
 558}
 559
 560impl OpenRouterEventMapper {
 561    pub fn new() -> Self {
 562        Self {
 563            tool_calls_by_index: HashMap::default(),
 564            reasoning_details: None,
 565        }
 566    }
 567
 568    pub fn map_stream(
 569        mut self,
 570        events: Pin<
 571            Box<
 572                dyn Send + Stream<Item = Result<ResponseStreamEvent, open_router::OpenRouterError>>,
 573            >,
 574        >,
 575    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
 576    {
 577        events.flat_map(move |event| {
 578            futures::stream::iter(match event {
 579                Ok(event) => self.map_event(event),
 580                Err(error) => vec![Err(error.into())],
 581            })
 582        })
 583    }
 584
 585    pub fn map_event(
 586        &mut self,
 587        event: ResponseStreamEvent,
 588    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 589        let Some(choice) = event.choices.first() else {
 590            return vec![Err(LanguageModelCompletionError::from(anyhow!(
 591                "Response contained no choices"
 592            )))];
 593        };
 594
 595        let mut events = Vec::new();
 596
 597        if let Some(details) = choice.delta.reasoning_details.clone() {
 598            // Emit reasoning_details immediately
 599            events.push(Ok(LanguageModelCompletionEvent::ReasoningDetails(
 600                details.clone(),
 601            )));
 602            self.reasoning_details = Some(details);
 603        }
 604
 605        if let Some(reasoning) = choice.delta.reasoning.clone() {
 606            events.push(Ok(LanguageModelCompletionEvent::Thinking {
 607                text: reasoning,
 608                signature: None,
 609            }));
 610        }
 611
 612        if let Some(content) = choice.delta.content.clone() {
 613            // OpenRouter send empty content string with the reasoning content
 614            // This is a workaround for the OpenRouter API bug
 615            if !content.is_empty() {
 616                events.push(Ok(LanguageModelCompletionEvent::Text(content)));
 617            }
 618        }
 619
 620        if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
 621            for tool_call in tool_calls {
 622                let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
 623
 624                if let Some(tool_id) = tool_call.id.clone() {
 625                    entry.id = tool_id;
 626                }
 627
 628                if let Some(function) = tool_call.function.as_ref() {
 629                    if let Some(name) = function.name.clone() {
 630                        entry.name = name;
 631                    }
 632
 633                    if let Some(arguments) = function.arguments.clone() {
 634                        entry.arguments.push_str(&arguments);
 635                    }
 636
 637                    if let Some(signature) = function.thought_signature.clone() {
 638                        entry.thought_signature = Some(signature);
 639                    }
 640                }
 641            }
 642        }
 643
 644        if let Some(usage) = event.usage {
 645            events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
 646                input_tokens: usage.prompt_tokens,
 647                output_tokens: usage.completion_tokens,
 648                cache_creation_input_tokens: 0,
 649                cache_read_input_tokens: 0,
 650            })));
 651        }
 652
 653        match choice.finish_reason.as_deref() {
 654            Some("stop") => {
 655                // Don't emit reasoning_details here - already emitted immediately when captured
 656                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
 657            }
 658            Some("tool_calls") => {
 659                events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
 660                    match serde_json::Value::from_str(&tool_call.arguments) {
 661                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
 662                            LanguageModelToolUse {
 663                                id: tool_call.id.clone().into(),
 664                                name: tool_call.name.as_str().into(),
 665                                is_input_complete: true,
 666                                input,
 667                                raw_input: tool_call.arguments.clone(),
 668                                thought_signature: tool_call.thought_signature.clone(),
 669                            },
 670                        )),
 671                        Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
 672                            id: tool_call.id.clone().into(),
 673                            tool_name: tool_call.name.as_str().into(),
 674                            raw_input: tool_call.arguments.clone().into(),
 675                            json_parse_error: error.to_string(),
 676                        }),
 677                    }
 678                }));
 679
 680                // Don't emit reasoning_details here - already emitted immediately when captured
 681                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
 682            }
 683            Some(stop_reason) => {
 684                log::error!("Unexpected OpenRouter stop_reason: {stop_reason:?}",);
 685                // Don't emit reasoning_details here - already emitted immediately when captured
 686                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
 687            }
 688            None => {}
 689        }
 690
 691        events
 692    }
 693}
 694
 695#[derive(Default)]
 696struct RawToolCall {
 697    id: String,
 698    name: String,
 699    arguments: String,
 700    thought_signature: Option<String>,
 701}
 702
 703pub fn count_open_router_tokens(
 704    request: LanguageModelRequest,
 705    _model: open_router::Model,
 706    cx: &App,
 707) -> BoxFuture<'static, Result<u64>> {
 708    cx.background_spawn(async move {
 709        let messages = request
 710            .messages
 711            .into_iter()
 712            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
 713                role: match message.role {
 714                    Role::User => "user".into(),
 715                    Role::Assistant => "assistant".into(),
 716                    Role::System => "system".into(),
 717                },
 718                content: Some(message.string_contents()),
 719                name: None,
 720                function_call: None,
 721            })
 722            .collect::<Vec<_>>();
 723
 724        tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages).map(|tokens| tokens as u64)
 725    })
 726    .boxed()
 727}
 728
 729struct ConfigurationView {
 730    api_key_editor: Entity<InputField>,
 731    state: Entity<State>,
 732    load_credentials_task: Option<Task<()>>,
 733}
 734
 735impl ConfigurationView {
 736    fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 737        let api_key_editor = cx.new(|cx| {
 738            InputField::new(
 739                window,
 740                cx,
 741                "sk_or_000000000000000000000000000000000000000000000000",
 742            )
 743        });
 744
 745        cx.observe(&state, |_, _, cx| {
 746            cx.notify();
 747        })
 748        .detach();
 749
 750        let load_credentials_task = Some(cx.spawn_in(window, {
 751            let state = state.clone();
 752            async move |this, cx| {
 753                if let Some(task) = Some(state.update(cx, |state, cx| state.authenticate(cx))) {
 754                    let _ = task.await;
 755                }
 756
 757                this.update(cx, |this, cx| {
 758                    this.load_credentials_task = None;
 759                    cx.notify();
 760                })
 761                .log_err();
 762            }
 763        }));
 764
 765        Self {
 766            api_key_editor,
 767            state,
 768            load_credentials_task,
 769        }
 770    }
 771
 772    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 773        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
 774        if api_key.is_empty() {
 775            return;
 776        }
 777
 778        // url changes can cause the editor to be displayed again
 779        self.api_key_editor
 780            .update(cx, |editor, cx| editor.set_text("", window, cx));
 781
 782        let state = self.state.clone();
 783        cx.spawn_in(window, async move |_, cx| {
 784            state
 785                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))
 786                .await
 787        })
 788        .detach_and_log_err(cx);
 789    }
 790
 791    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 792        self.api_key_editor
 793            .update(cx, |editor, cx| editor.set_text("", window, cx));
 794
 795        let state = self.state.clone();
 796        cx.spawn_in(window, async move |_, cx| {
 797            state
 798                .update(cx, |state, cx| state.set_api_key(None, cx))
 799                .await
 800        })
 801        .detach_and_log_err(cx);
 802    }
 803
 804    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
 805        !self.state.read(cx).is_authenticated()
 806    }
 807}
 808
 809impl Render for ConfigurationView {
 810    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 811        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
 812        let configured_card_label = if env_var_set {
 813            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
 814        } else {
 815            let api_url = OpenRouterLanguageModelProvider::api_url(cx);
 816            if api_url == OPEN_ROUTER_API_URL {
 817                "API key configured".to_string()
 818            } else {
 819                format!("API key configured for {}", api_url)
 820            }
 821        };
 822
 823        if self.load_credentials_task.is_some() {
 824            div()
 825                .child(Label::new("Loading credentials..."))
 826                .into_any_element()
 827        } else if self.should_render_editor(cx) {
 828            v_flex()
 829                .size_full()
 830                .on_action(cx.listener(Self::save_api_key))
 831                .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
 832                .child(
 833                    List::new()
 834                        .child(
 835                            ListBulletItem::new("")
 836                                .child(Label::new("Create an API key by visiting"))
 837                                .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
 838                        )
 839                        .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
 840                        )
 841                        .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
 842                        ),
 843                )
 844                .child(self.api_key_editor.clone())
 845                .child(
 846                    Label::new(
 847                        format!("You can also set the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
 848                    )
 849                    .size(LabelSize::Small).color(Color::Muted),
 850                )
 851                .into_any_element()
 852        } else {
 853            ConfiguredApiCard::new(configured_card_label)
 854                .disabled(env_var_set)
 855                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
 856                .when(env_var_set, |this| {
 857                    this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
 858                })
 859                .into_any_element()
 860        }
 861    }
 862}
 863
 864#[cfg(test)]
 865mod tests {
 866    use super::*;
 867
 868    use open_router::{ChoiceDelta, FunctionChunk, ResponseMessageDelta, ToolCallChunk};
 869
 870    #[gpui::test]
 871    async fn test_reasoning_details_preservation_with_tool_calls() {
 872        // This test verifies that reasoning_details are properly captured and preserved
 873        // when a model uses tool calling with reasoning/thinking tokens.
 874        //
 875        // The key regression this prevents:
 876        // - OpenRouter sends multiple reasoning_details updates during streaming
 877        // - First with actual content (encrypted reasoning data)
 878        // - Then with empty array on completion
 879        // - We must NOT overwrite the real data with the empty array
 880
 881        let mut mapper = OpenRouterEventMapper::new();
 882
 883        // Simulate the streaming events as they come from OpenRouter/Gemini
 884        let events = vec![
 885            // Event 1: Initial reasoning details with text
 886            ResponseStreamEvent {
 887                id: Some("response_123".into()),
 888                created: 1234567890,
 889                model: "google/gemini-3-pro-preview".into(),
 890                choices: vec![ChoiceDelta {
 891                    index: 0,
 892                    delta: ResponseMessageDelta {
 893                        role: None,
 894                        content: None,
 895                        reasoning: None,
 896                        tool_calls: None,
 897                        reasoning_details: Some(serde_json::json!([
 898                            {
 899                                "type": "reasoning.text",
 900                                "text": "Let me analyze this request...",
 901                                "format": "google-gemini-v1",
 902                                "index": 0
 903                            }
 904                        ])),
 905                    },
 906                    finish_reason: None,
 907                }],
 908                usage: None,
 909            },
 910            // Event 2: More reasoning details
 911            ResponseStreamEvent {
 912                id: Some("response_123".into()),
 913                created: 1234567890,
 914                model: "google/gemini-3-pro-preview".into(),
 915                choices: vec![ChoiceDelta {
 916                    index: 0,
 917                    delta: ResponseMessageDelta {
 918                        role: None,
 919                        content: None,
 920                        reasoning: None,
 921                        tool_calls: None,
 922                        reasoning_details: Some(serde_json::json!([
 923                            {
 924                                "type": "reasoning.encrypted",
 925                                "data": "EtgDCtUDAdHtim9OF5jm4aeZSBAtl/randomized123",
 926                                "format": "google-gemini-v1",
 927                                "index": 0,
 928                                "id": "tool_call_abc123"
 929                            }
 930                        ])),
 931                    },
 932                    finish_reason: None,
 933                }],
 934                usage: None,
 935            },
 936            // Event 3: Tool call starts
 937            ResponseStreamEvent {
 938                id: Some("response_123".into()),
 939                created: 1234567890,
 940                model: "google/gemini-3-pro-preview".into(),
 941                choices: vec![ChoiceDelta {
 942                    index: 0,
 943                    delta: ResponseMessageDelta {
 944                        role: None,
 945                        content: None,
 946                        reasoning: None,
 947                        tool_calls: Some(vec![ToolCallChunk {
 948                            index: 0,
 949                            id: Some("tool_call_abc123".into()),
 950                            function: Some(FunctionChunk {
 951                                name: Some("list_directory".into()),
 952                                arguments: Some("{\"path\":\"test\"}".into()),
 953                                thought_signature: Some("sha256:test_signature_xyz789".into()),
 954                            }),
 955                        }]),
 956                        reasoning_details: None,
 957                    },
 958                    finish_reason: None,
 959                }],
 960                usage: None,
 961            },
 962            // Event 4: Empty reasoning_details on tool_calls finish
 963            // This is the critical event - we must not overwrite with this empty array!
 964            ResponseStreamEvent {
 965                id: Some("response_123".into()),
 966                created: 1234567890,
 967                model: "google/gemini-3-pro-preview".into(),
 968                choices: vec![ChoiceDelta {
 969                    index: 0,
 970                    delta: ResponseMessageDelta {
 971                        role: None,
 972                        content: None,
 973                        reasoning: None,
 974                        tool_calls: None,
 975                        reasoning_details: Some(serde_json::json!([])),
 976                    },
 977                    finish_reason: Some("tool_calls".into()),
 978                }],
 979                usage: None,
 980            },
 981        ];
 982
 983        // Process all events
 984        let mut collected_events = Vec::new();
 985        for event in events {
 986            let mapped = mapper.map_event(event);
 987            collected_events.extend(mapped);
 988        }
 989
 990        // Verify we got the expected events
 991        let mut has_tool_use = false;
 992        let mut reasoning_details_events = Vec::new();
 993        let mut thought_signature_value = None;
 994
 995        for event_result in collected_events {
 996            match event_result {
 997                Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 998                    has_tool_use = true;
 999                    assert_eq!(tool_use.id.to_string(), "tool_call_abc123");
1000                    assert_eq!(tool_use.name.as_ref(), "list_directory");
1001                    thought_signature_value = tool_use.thought_signature.clone();
1002                }
1003                Ok(LanguageModelCompletionEvent::ReasoningDetails(details)) => {
1004                    reasoning_details_events.push(details);
1005                }
1006                _ => {}
1007            }
1008        }
1009
1010        // Assertions
1011        assert!(has_tool_use, "Should have emitted ToolUse event");
1012        assert!(
1013            !reasoning_details_events.is_empty(),
1014            "Should have emitted ReasoningDetails events"
1015        );
1016
1017        // We should have received multiple reasoning_details events (text, encrypted, empty)
1018        // The agent layer is responsible for keeping only the first non-empty one
1019        assert!(
1020            reasoning_details_events.len() >= 2,
1021            "Should have multiple reasoning_details events from streaming"
1022        );
1023
1024        // Verify at least one contains the encrypted data
1025        let has_encrypted = reasoning_details_events.iter().any(|details| {
1026            if let serde_json::Value::Array(arr) = details {
1027                arr.iter().any(|item| {
1028                    item["type"] == "reasoning.encrypted"
1029                        && item["data"]
1030                            .as_str()
1031                            .map_or(false, |s| s.contains("EtgDCtUDAdHtim9OF5jm4aeZSBAtl"))
1032                })
1033            } else {
1034                false
1035            }
1036        });
1037        assert!(
1038            has_encrypted,
1039            "Should have at least one reasoning_details with encrypted data"
1040        );
1041
1042        // Verify thought_signature was captured
1043        assert!(
1044            thought_signature_value.is_some(),
1045            "Tool use should have thought_signature"
1046        );
1047        assert_eq!(
1048            thought_signature_value.unwrap(),
1049            "sha256:test_signature_xyz789"
1050        );
1051    }
1052
1053    #[gpui::test]
1054    async fn test_agent_prevents_empty_reasoning_details_overwrite() {
1055        // This test verifies that the agent layer prevents empty reasoning_details
1056        // from overwriting non-empty ones, even though the mapper emits all events.
1057
1058        // Simulate what the agent does when it receives multiple ReasoningDetails events
1059        let mut agent_reasoning_details: Option<serde_json::Value> = None;
1060
1061        let events = vec![
1062            // First event: non-empty reasoning_details
1063            serde_json::json!([
1064                {
1065                    "type": "reasoning.encrypted",
1066                    "data": "real_data_here",
1067                    "format": "google-gemini-v1"
1068                }
1069            ]),
1070            // Second event: empty array (should not overwrite)
1071            serde_json::json!([]),
1072        ];
1073
1074        for details in events {
1075            // This mimics the agent's logic: only store if we don't already have it
1076            if agent_reasoning_details.is_none() {
1077                agent_reasoning_details = Some(details);
1078            }
1079        }
1080
1081        // Verify the agent kept the first non-empty reasoning_details
1082        assert!(agent_reasoning_details.is_some());
1083        let final_details = agent_reasoning_details.unwrap();
1084        if let serde_json::Value::Array(arr) = &final_details {
1085            assert!(
1086                !arr.is_empty(),
1087                "Agent should have kept the non-empty reasoning_details"
1088            );
1089            assert_eq!(arr[0]["data"], "real_data_here");
1090        } else {
1091            panic!("Expected array");
1092        }
1093    }
1094}