open_router.rs

   1use anyhow::{Result, anyhow};
   2use collections::HashMap;
   3use futures::{FutureExt, Stream, StreamExt, future, future::BoxFuture};
   4use gpui::{AnyView, App, AsyncApp, Context, Entity, SharedString, Task};
   5use http_client::HttpClient;
   6use language_model::{
   7    ApiKeyState, AuthenticateError, EnvVar, 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) -> IconName {
 184        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 Ok((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        }) else {
 280            return future::ready(Err(anyhow!("App state dropped").into())).boxed();
 281        };
 282
 283        async move {
 284            let Some(api_key) = api_key else {
 285                return Err(LanguageModelCompletionError::NoApiKey {
 286                    provider: PROVIDER_NAME,
 287                });
 288            };
 289            let request =
 290                open_router::stream_completion(http_client.as_ref(), &api_url, &api_key, request);
 291            request.await.map_err(Into::into)
 292        }
 293        .boxed()
 294    }
 295}
 296
 297impl LanguageModel for OpenRouterLanguageModel {
 298    fn id(&self) -> LanguageModelId {
 299        self.id.clone()
 300    }
 301
 302    fn name(&self) -> LanguageModelName {
 303        LanguageModelName::from(self.model.display_name().to_string())
 304    }
 305
 306    fn provider_id(&self) -> LanguageModelProviderId {
 307        PROVIDER_ID
 308    }
 309
 310    fn provider_name(&self) -> LanguageModelProviderName {
 311        PROVIDER_NAME
 312    }
 313
 314    fn supports_tools(&self) -> bool {
 315        self.model.supports_tool_calls()
 316    }
 317
 318    fn tool_input_format(&self) -> LanguageModelToolSchemaFormat {
 319        let model_id = self.model.id().trim().to_lowercase();
 320        if model_id.contains("gemini") || model_id.contains("grok") {
 321            LanguageModelToolSchemaFormat::JsonSchemaSubset
 322        } else {
 323            LanguageModelToolSchemaFormat::JsonSchema
 324        }
 325    }
 326
 327    fn telemetry_id(&self) -> String {
 328        format!("openrouter/{}", self.model.id())
 329    }
 330
 331    fn max_token_count(&self) -> u64 {
 332        self.model.max_token_count()
 333    }
 334
 335    fn max_output_tokens(&self) -> Option<u64> {
 336        self.model.max_output_tokens()
 337    }
 338
 339    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
 340        match choice {
 341            LanguageModelToolChoice::Auto => true,
 342            LanguageModelToolChoice::Any => true,
 343            LanguageModelToolChoice::None => true,
 344        }
 345    }
 346
 347    fn supports_images(&self) -> bool {
 348        self.model.supports_images.unwrap_or(false)
 349    }
 350
 351    fn count_tokens(
 352        &self,
 353        request: LanguageModelRequest,
 354        cx: &App,
 355    ) -> BoxFuture<'static, Result<u64>> {
 356        count_open_router_tokens(request, self.model.clone(), cx)
 357    }
 358
 359    fn stream_completion(
 360        &self,
 361        request: LanguageModelRequest,
 362        cx: &AsyncApp,
 363    ) -> BoxFuture<
 364        'static,
 365        Result<
 366            futures::stream::BoxStream<
 367                'static,
 368                Result<LanguageModelCompletionEvent, LanguageModelCompletionError>,
 369            >,
 370            LanguageModelCompletionError,
 371        >,
 372    > {
 373        let request = into_open_router(request, &self.model, self.max_output_tokens());
 374        let request = self.stream_completion(request, cx);
 375        let future = self.request_limiter.stream(async move {
 376            let response = request.await?;
 377            Ok(OpenRouterEventMapper::new().map_stream(response))
 378        });
 379        async move { Ok(future.await?.boxed()) }.boxed()
 380    }
 381}
 382
 383pub fn into_open_router(
 384    request: LanguageModelRequest,
 385    model: &Model,
 386    max_output_tokens: Option<u64>,
 387) -> open_router::Request {
 388    let mut messages = Vec::new();
 389    for message in request.messages {
 390        let reasoning_details = message.reasoning_details.clone();
 391        for content in message.content {
 392            match content {
 393                MessageContent::Text(text) => add_message_content_part(
 394                    open_router::MessagePart::Text { text },
 395                    message.role,
 396                    &mut messages,
 397                ),
 398                MessageContent::Thinking { .. } => {}
 399                MessageContent::RedactedThinking(_) => {}
 400                MessageContent::Image(image) => {
 401                    add_message_content_part(
 402                        open_router::MessagePart::Image {
 403                            image_url: image.to_base64_url(),
 404                        },
 405                        message.role,
 406                        &mut messages,
 407                    );
 408                }
 409                MessageContent::ToolUse(tool_use) => {
 410                    let tool_call = open_router::ToolCall {
 411                        id: tool_use.id.to_string(),
 412                        content: open_router::ToolCallContent::Function {
 413                            function: open_router::FunctionContent {
 414                                name: tool_use.name.to_string(),
 415                                arguments: serde_json::to_string(&tool_use.input)
 416                                    .unwrap_or_default(),
 417                                thought_signature: tool_use.thought_signature.clone(),
 418                            },
 419                        },
 420                    };
 421
 422                    if let Some(open_router::RequestMessage::Assistant {
 423                        tool_calls,
 424                        reasoning_details: existing_reasoning,
 425                        ..
 426                    }) = messages.last_mut()
 427                    {
 428                        tool_calls.push(tool_call);
 429                        if existing_reasoning.is_none() && reasoning_details.is_some() {
 430                            *existing_reasoning = reasoning_details.clone();
 431                        }
 432                    } else {
 433                        messages.push(open_router::RequestMessage::Assistant {
 434                            content: None,
 435                            tool_calls: vec![tool_call],
 436                            reasoning_details: reasoning_details.clone(),
 437                        });
 438                    }
 439                }
 440                MessageContent::ToolResult(tool_result) => {
 441                    let content = match &tool_result.content {
 442                        LanguageModelToolResultContent::Text(text) => {
 443                            vec![open_router::MessagePart::Text {
 444                                text: text.to_string(),
 445                            }]
 446                        }
 447                        LanguageModelToolResultContent::Image(image) => {
 448                            vec![open_router::MessagePart::Image {
 449                                image_url: image.to_base64_url(),
 450                            }]
 451                        }
 452                    };
 453
 454                    messages.push(open_router::RequestMessage::Tool {
 455                        content: content.into(),
 456                        tool_call_id: tool_result.tool_use_id.to_string(),
 457                    });
 458                }
 459            }
 460        }
 461    }
 462
 463    open_router::Request {
 464        model: model.id().into(),
 465        messages,
 466        stream: true,
 467        stop: request.stop,
 468        temperature: request.temperature.unwrap_or(0.4),
 469        max_tokens: max_output_tokens,
 470        parallel_tool_calls: if model.supports_parallel_tool_calls() && !request.tools.is_empty() {
 471            Some(false)
 472        } else {
 473            None
 474        },
 475        usage: open_router::RequestUsage { include: true },
 476        reasoning: if request.thinking_allowed
 477            && let OpenRouterModelMode::Thinking { budget_tokens } = model.mode
 478        {
 479            Some(open_router::Reasoning {
 480                effort: None,
 481                max_tokens: budget_tokens,
 482                exclude: Some(false),
 483                enabled: Some(true),
 484            })
 485        } else {
 486            None
 487        },
 488        tools: request
 489            .tools
 490            .into_iter()
 491            .map(|tool| open_router::ToolDefinition::Function {
 492                function: open_router::FunctionDefinition {
 493                    name: tool.name,
 494                    description: Some(tool.description),
 495                    parameters: Some(tool.input_schema),
 496                },
 497            })
 498            .collect(),
 499        tool_choice: request.tool_choice.map(|choice| match choice {
 500            LanguageModelToolChoice::Auto => open_router::ToolChoice::Auto,
 501            LanguageModelToolChoice::Any => open_router::ToolChoice::Required,
 502            LanguageModelToolChoice::None => open_router::ToolChoice::None,
 503        }),
 504        provider: model.provider.clone(),
 505    }
 506}
 507
 508fn add_message_content_part(
 509    new_part: open_router::MessagePart,
 510    role: Role,
 511    messages: &mut Vec<open_router::RequestMessage>,
 512) {
 513    match (role, messages.last_mut()) {
 514        (Role::User, Some(open_router::RequestMessage::User { content }))
 515        | (Role::System, Some(open_router::RequestMessage::System { content })) => {
 516            content.push_part(new_part);
 517        }
 518        (
 519            Role::Assistant,
 520            Some(open_router::RequestMessage::Assistant {
 521                content: Some(content),
 522                ..
 523            }),
 524        ) => {
 525            content.push_part(new_part);
 526        }
 527        _ => {
 528            messages.push(match role {
 529                Role::User => open_router::RequestMessage::User {
 530                    content: open_router::MessageContent::from(vec![new_part]),
 531                },
 532                Role::Assistant => open_router::RequestMessage::Assistant {
 533                    content: Some(open_router::MessageContent::from(vec![new_part])),
 534                    tool_calls: Vec::new(),
 535                    reasoning_details: None,
 536                },
 537                Role::System => open_router::RequestMessage::System {
 538                    content: open_router::MessageContent::from(vec![new_part]),
 539                },
 540            });
 541        }
 542    }
 543}
 544
 545pub struct OpenRouterEventMapper {
 546    tool_calls_by_index: HashMap<usize, RawToolCall>,
 547    reasoning_details: Option<serde_json::Value>,
 548}
 549
 550impl OpenRouterEventMapper {
 551    pub fn new() -> Self {
 552        Self {
 553            tool_calls_by_index: HashMap::default(),
 554            reasoning_details: None,
 555        }
 556    }
 557
 558    pub fn map_stream(
 559        mut self,
 560        events: Pin<
 561            Box<
 562                dyn Send + Stream<Item = Result<ResponseStreamEvent, open_router::OpenRouterError>>,
 563            >,
 564        >,
 565    ) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>
 566    {
 567        events.flat_map(move |event| {
 568            futures::stream::iter(match event {
 569                Ok(event) => self.map_event(event),
 570                Err(error) => vec![Err(error.into())],
 571            })
 572        })
 573    }
 574
 575    pub fn map_event(
 576        &mut self,
 577        event: ResponseStreamEvent,
 578    ) -> Vec<Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 579        let Some(choice) = event.choices.first() else {
 580            return vec![Err(LanguageModelCompletionError::from(anyhow!(
 581                "Response contained no choices"
 582            )))];
 583        };
 584
 585        let mut events = Vec::new();
 586
 587        if let Some(details) = choice.delta.reasoning_details.clone() {
 588            // Emit reasoning_details immediately
 589            events.push(Ok(LanguageModelCompletionEvent::ReasoningDetails(
 590                details.clone(),
 591            )));
 592            self.reasoning_details = Some(details);
 593        }
 594
 595        if let Some(reasoning) = choice.delta.reasoning.clone() {
 596            events.push(Ok(LanguageModelCompletionEvent::Thinking {
 597                text: reasoning,
 598                signature: None,
 599            }));
 600        }
 601
 602        if let Some(content) = choice.delta.content.clone() {
 603            // OpenRouter send empty content string with the reasoning content
 604            // This is a workaround for the OpenRouter API bug
 605            if !content.is_empty() {
 606                events.push(Ok(LanguageModelCompletionEvent::Text(content)));
 607            }
 608        }
 609
 610        if let Some(tool_calls) = choice.delta.tool_calls.as_ref() {
 611            for tool_call in tool_calls {
 612                let entry = self.tool_calls_by_index.entry(tool_call.index).or_default();
 613
 614                if let Some(tool_id) = tool_call.id.clone() {
 615                    entry.id = tool_id;
 616                }
 617
 618                if let Some(function) = tool_call.function.as_ref() {
 619                    if let Some(name) = function.name.clone() {
 620                        entry.name = name;
 621                    }
 622
 623                    if let Some(arguments) = function.arguments.clone() {
 624                        entry.arguments.push_str(&arguments);
 625                    }
 626
 627                    if let Some(signature) = function.thought_signature.clone() {
 628                        entry.thought_signature = Some(signature);
 629                    }
 630                }
 631            }
 632        }
 633
 634        if let Some(usage) = event.usage {
 635            events.push(Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
 636                input_tokens: usage.prompt_tokens,
 637                output_tokens: usage.completion_tokens,
 638                cache_creation_input_tokens: 0,
 639                cache_read_input_tokens: 0,
 640            })));
 641        }
 642
 643        match choice.finish_reason.as_deref() {
 644            Some("stop") => {
 645                // Don't emit reasoning_details here - already emitted immediately when captured
 646                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
 647            }
 648            Some("tool_calls") => {
 649                events.extend(self.tool_calls_by_index.drain().map(|(_, tool_call)| {
 650                    match serde_json::Value::from_str(&tool_call.arguments) {
 651                        Ok(input) => Ok(LanguageModelCompletionEvent::ToolUse(
 652                            LanguageModelToolUse {
 653                                id: tool_call.id.clone().into(),
 654                                name: tool_call.name.as_str().into(),
 655                                is_input_complete: true,
 656                                input,
 657                                raw_input: tool_call.arguments.clone(),
 658                                thought_signature: tool_call.thought_signature.clone(),
 659                            },
 660                        )),
 661                        Err(error) => Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
 662                            id: tool_call.id.clone().into(),
 663                            tool_name: tool_call.name.as_str().into(),
 664                            raw_input: tool_call.arguments.clone().into(),
 665                            json_parse_error: error.to_string(),
 666                        }),
 667                    }
 668                }));
 669
 670                // Don't emit reasoning_details here - already emitted immediately when captured
 671                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::ToolUse)));
 672            }
 673            Some(stop_reason) => {
 674                log::error!("Unexpected OpenRouter stop_reason: {stop_reason:?}",);
 675                // Don't emit reasoning_details here - already emitted immediately when captured
 676                events.push(Ok(LanguageModelCompletionEvent::Stop(StopReason::EndTurn)));
 677            }
 678            None => {}
 679        }
 680
 681        events
 682    }
 683}
 684
 685#[derive(Default)]
 686struct RawToolCall {
 687    id: String,
 688    name: String,
 689    arguments: String,
 690    thought_signature: Option<String>,
 691}
 692
 693pub fn count_open_router_tokens(
 694    request: LanguageModelRequest,
 695    _model: open_router::Model,
 696    cx: &App,
 697) -> BoxFuture<'static, Result<u64>> {
 698    cx.background_spawn(async move {
 699        let messages = request
 700            .messages
 701            .into_iter()
 702            .map(|message| tiktoken_rs::ChatCompletionRequestMessage {
 703                role: match message.role {
 704                    Role::User => "user".into(),
 705                    Role::Assistant => "assistant".into(),
 706                    Role::System => "system".into(),
 707                },
 708                content: Some(message.string_contents()),
 709                name: None,
 710                function_call: None,
 711            })
 712            .collect::<Vec<_>>();
 713
 714        tiktoken_rs::num_tokens_from_messages("gpt-4o", &messages).map(|tokens| tokens as u64)
 715    })
 716    .boxed()
 717}
 718
 719struct ConfigurationView {
 720    api_key_editor: Entity<InputField>,
 721    state: Entity<State>,
 722    load_credentials_task: Option<Task<()>>,
 723}
 724
 725impl ConfigurationView {
 726    fn new(state: Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
 727        let api_key_editor = cx.new(|cx| {
 728            InputField::new(
 729                window,
 730                cx,
 731                "sk_or_000000000000000000000000000000000000000000000000",
 732            )
 733        });
 734
 735        cx.observe(&state, |_, _, cx| {
 736            cx.notify();
 737        })
 738        .detach();
 739
 740        let load_credentials_task = Some(cx.spawn_in(window, {
 741            let state = state.clone();
 742            async move |this, cx| {
 743                if let Some(task) = state
 744                    .update(cx, |state, cx| state.authenticate(cx))
 745                    .log_err()
 746                {
 747                    let _ = task.await;
 748                }
 749
 750                this.update(cx, |this, cx| {
 751                    this.load_credentials_task = None;
 752                    cx.notify();
 753                })
 754                .log_err();
 755            }
 756        }));
 757
 758        Self {
 759            api_key_editor,
 760            state,
 761            load_credentials_task,
 762        }
 763    }
 764
 765    fn save_api_key(&mut self, _: &menu::Confirm, window: &mut Window, cx: &mut Context<Self>) {
 766        let api_key = self.api_key_editor.read(cx).text(cx).trim().to_string();
 767        if api_key.is_empty() {
 768            return;
 769        }
 770
 771        // url changes can cause the editor to be displayed again
 772        self.api_key_editor
 773            .update(cx, |editor, cx| editor.set_text("", window, cx));
 774
 775        let state = self.state.clone();
 776        cx.spawn_in(window, async move |_, cx| {
 777            state
 778                .update(cx, |state, cx| state.set_api_key(Some(api_key), cx))?
 779                .await
 780        })
 781        .detach_and_log_err(cx);
 782    }
 783
 784    fn reset_api_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 785        self.api_key_editor
 786            .update(cx, |editor, cx| editor.set_text("", window, cx));
 787
 788        let state = self.state.clone();
 789        cx.spawn_in(window, async move |_, cx| {
 790            state
 791                .update(cx, |state, cx| state.set_api_key(None, cx))?
 792                .await
 793        })
 794        .detach_and_log_err(cx);
 795    }
 796
 797    fn should_render_editor(&self, cx: &mut Context<Self>) -> bool {
 798        !self.state.read(cx).is_authenticated()
 799    }
 800}
 801
 802impl Render for ConfigurationView {
 803    fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
 804        let env_var_set = self.state.read(cx).api_key_state.is_from_env_var();
 805        let configured_card_label = if env_var_set {
 806            format!("API key set in {API_KEY_ENV_VAR_NAME} environment variable")
 807        } else {
 808            let api_url = OpenRouterLanguageModelProvider::api_url(cx);
 809            if api_url == OPEN_ROUTER_API_URL {
 810                "API key configured".to_string()
 811            } else {
 812                format!("API key configured for {}", api_url)
 813            }
 814        };
 815
 816        if self.load_credentials_task.is_some() {
 817            div()
 818                .child(Label::new("Loading credentials..."))
 819                .into_any_element()
 820        } else if self.should_render_editor(cx) {
 821            v_flex()
 822                .size_full()
 823                .on_action(cx.listener(Self::save_api_key))
 824                .child(Label::new("To use Zed's agent with OpenRouter, you need to add an API key. Follow these steps:"))
 825                .child(
 826                    List::new()
 827                        .child(
 828                            ListBulletItem::new("")
 829                                .child(Label::new("Create an API key by visiting"))
 830                                .child(ButtonLink::new("OpenRouter's console", "https://openrouter.ai/keys"))
 831                        )
 832                        .child(ListBulletItem::new("Ensure your OpenRouter account has credits")
 833                        )
 834                        .child(ListBulletItem::new("Paste your API key below and hit enter to start using the assistant")
 835                        ),
 836                )
 837                .child(self.api_key_editor.clone())
 838                .child(
 839                    Label::new(
 840                        format!("You can also assign the {API_KEY_ENV_VAR_NAME} environment variable and restart Zed."),
 841                    )
 842                    .size(LabelSize::Small).color(Color::Muted),
 843                )
 844                .into_any_element()
 845        } else {
 846            ConfiguredApiCard::new(configured_card_label)
 847                .disabled(env_var_set)
 848                .on_click(cx.listener(|this, _, window, cx| this.reset_api_key(window, cx)))
 849                .when(env_var_set, |this| {
 850                    this.tooltip_label(format!("To reset your API key, unset the {API_KEY_ENV_VAR_NAME} environment variable."))
 851                })
 852                .into_any_element()
 853        }
 854    }
 855}
 856
 857#[cfg(test)]
 858mod tests {
 859    use super::*;
 860
 861    use open_router::{ChoiceDelta, FunctionChunk, ResponseMessageDelta, ToolCallChunk};
 862
 863    #[gpui::test]
 864    async fn test_reasoning_details_preservation_with_tool_calls() {
 865        // This test verifies that reasoning_details are properly captured and preserved
 866        // when a model uses tool calling with reasoning/thinking tokens.
 867        //
 868        // The key regression this prevents:
 869        // - OpenRouter sends multiple reasoning_details updates during streaming
 870        // - First with actual content (encrypted reasoning data)
 871        // - Then with empty array on completion
 872        // - We must NOT overwrite the real data with the empty array
 873
 874        let mut mapper = OpenRouterEventMapper::new();
 875
 876        // Simulate the streaming events as they come from OpenRouter/Gemini
 877        let events = vec![
 878            // Event 1: Initial reasoning details with text
 879            ResponseStreamEvent {
 880                id: Some("response_123".into()),
 881                created: 1234567890,
 882                model: "google/gemini-3-pro-preview".into(),
 883                choices: vec![ChoiceDelta {
 884                    index: 0,
 885                    delta: ResponseMessageDelta {
 886                        role: None,
 887                        content: None,
 888                        reasoning: None,
 889                        tool_calls: None,
 890                        reasoning_details: Some(serde_json::json!([
 891                            {
 892                                "type": "reasoning.text",
 893                                "text": "Let me analyze this request...",
 894                                "format": "google-gemini-v1",
 895                                "index": 0
 896                            }
 897                        ])),
 898                    },
 899                    finish_reason: None,
 900                }],
 901                usage: None,
 902            },
 903            // Event 2: More reasoning details
 904            ResponseStreamEvent {
 905                id: Some("response_123".into()),
 906                created: 1234567890,
 907                model: "google/gemini-3-pro-preview".into(),
 908                choices: vec![ChoiceDelta {
 909                    index: 0,
 910                    delta: ResponseMessageDelta {
 911                        role: None,
 912                        content: None,
 913                        reasoning: None,
 914                        tool_calls: None,
 915                        reasoning_details: Some(serde_json::json!([
 916                            {
 917                                "type": "reasoning.encrypted",
 918                                "data": "EtgDCtUDAdHtim9OF5jm4aeZSBAtl/randomized123",
 919                                "format": "google-gemini-v1",
 920                                "index": 0,
 921                                "id": "tool_call_abc123"
 922                            }
 923                        ])),
 924                    },
 925                    finish_reason: None,
 926                }],
 927                usage: None,
 928            },
 929            // Event 3: Tool call starts
 930            ResponseStreamEvent {
 931                id: Some("response_123".into()),
 932                created: 1234567890,
 933                model: "google/gemini-3-pro-preview".into(),
 934                choices: vec![ChoiceDelta {
 935                    index: 0,
 936                    delta: ResponseMessageDelta {
 937                        role: None,
 938                        content: None,
 939                        reasoning: None,
 940                        tool_calls: Some(vec![ToolCallChunk {
 941                            index: 0,
 942                            id: Some("tool_call_abc123".into()),
 943                            function: Some(FunctionChunk {
 944                                name: Some("list_directory".into()),
 945                                arguments: Some("{\"path\":\"test\"}".into()),
 946                                thought_signature: Some("sha256:test_signature_xyz789".into()),
 947                            }),
 948                        }]),
 949                        reasoning_details: None,
 950                    },
 951                    finish_reason: None,
 952                }],
 953                usage: None,
 954            },
 955            // Event 4: Empty reasoning_details on tool_calls finish
 956            // This is the critical event - we must not overwrite with this empty array!
 957            ResponseStreamEvent {
 958                id: Some("response_123".into()),
 959                created: 1234567890,
 960                model: "google/gemini-3-pro-preview".into(),
 961                choices: vec![ChoiceDelta {
 962                    index: 0,
 963                    delta: ResponseMessageDelta {
 964                        role: None,
 965                        content: None,
 966                        reasoning: None,
 967                        tool_calls: None,
 968                        reasoning_details: Some(serde_json::json!([])),
 969                    },
 970                    finish_reason: Some("tool_calls".into()),
 971                }],
 972                usage: None,
 973            },
 974        ];
 975
 976        // Process all events
 977        let mut collected_events = Vec::new();
 978        for event in events {
 979            let mapped = mapper.map_event(event);
 980            collected_events.extend(mapped);
 981        }
 982
 983        // Verify we got the expected events
 984        let mut has_tool_use = false;
 985        let mut reasoning_details_events = Vec::new();
 986        let mut thought_signature_value = None;
 987
 988        for event_result in collected_events {
 989            match event_result {
 990                Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 991                    has_tool_use = true;
 992                    assert_eq!(tool_use.id.to_string(), "tool_call_abc123");
 993                    assert_eq!(tool_use.name.as_ref(), "list_directory");
 994                    thought_signature_value = tool_use.thought_signature.clone();
 995                }
 996                Ok(LanguageModelCompletionEvent::ReasoningDetails(details)) => {
 997                    reasoning_details_events.push(details);
 998                }
 999                _ => {}
1000            }
1001        }
1002
1003        // Assertions
1004        assert!(has_tool_use, "Should have emitted ToolUse event");
1005        assert!(
1006            !reasoning_details_events.is_empty(),
1007            "Should have emitted ReasoningDetails events"
1008        );
1009
1010        // We should have received multiple reasoning_details events (text, encrypted, empty)
1011        // The agent layer is responsible for keeping only the first non-empty one
1012        assert!(
1013            reasoning_details_events.len() >= 2,
1014            "Should have multiple reasoning_details events from streaming"
1015        );
1016
1017        // Verify at least one contains the encrypted data
1018        let has_encrypted = reasoning_details_events.iter().any(|details| {
1019            if let serde_json::Value::Array(arr) = details {
1020                arr.iter().any(|item| {
1021                    item["type"] == "reasoning.encrypted"
1022                        && item["data"]
1023                            .as_str()
1024                            .map_or(false, |s| s.contains("EtgDCtUDAdHtim9OF5jm4aeZSBAtl"))
1025                })
1026            } else {
1027                false
1028            }
1029        });
1030        assert!(
1031            has_encrypted,
1032            "Should have at least one reasoning_details with encrypted data"
1033        );
1034
1035        // Verify thought_signature was captured
1036        assert!(
1037            thought_signature_value.is_some(),
1038            "Tool use should have thought_signature"
1039        );
1040        assert_eq!(
1041            thought_signature_value.unwrap(),
1042            "sha256:test_signature_xyz789"
1043        );
1044    }
1045
1046    #[gpui::test]
1047    async fn test_agent_prevents_empty_reasoning_details_overwrite() {
1048        // This test verifies that the agent layer prevents empty reasoning_details
1049        // from overwriting non-empty ones, even though the mapper emits all events.
1050
1051        // Simulate what the agent does when it receives multiple ReasoningDetails events
1052        let mut agent_reasoning_details: Option<serde_json::Value> = None;
1053
1054        let events = vec![
1055            // First event: non-empty reasoning_details
1056            serde_json::json!([
1057                {
1058                    "type": "reasoning.encrypted",
1059                    "data": "real_data_here",
1060                    "format": "google-gemini-v1"
1061                }
1062            ]),
1063            // Second event: empty array (should not overwrite)
1064            serde_json::json!([]),
1065        ];
1066
1067        for details in events {
1068            // This mimics the agent's logic: only store if we don't already have it
1069            if agent_reasoning_details.is_none() {
1070                agent_reasoning_details = Some(details);
1071            }
1072        }
1073
1074        // Verify the agent kept the first non-empty reasoning_details
1075        assert!(agent_reasoning_details.is_some());
1076        let final_details = agent_reasoning_details.unwrap();
1077        if let serde_json::Value::Array(arr) = &final_details {
1078            assert!(
1079                !arr.is_empty(),
1080                "Agent should have kept the non-empty reasoning_details"
1081            );
1082            assert_eq!(arr[0]["data"], "real_data_here");
1083        } else {
1084            panic!("Expected array");
1085        }
1086    }
1087}