bedrock.rs

   1use std::pin::Pin;
   2use std::str::FromStr;
   3use std::sync::Arc;
   4
   5use crate::ui::InstructionListItem;
   6use anyhow::{Context as _, Result, anyhow};
   7use aws_config::stalled_stream_protection::StalledStreamProtectionConfig;
   8use aws_config::{BehaviorVersion, Region};
   9use aws_credential_types::Credentials;
  10use aws_http_client::AwsHttpClient;
  11use bedrock::bedrock_client::Client as BedrockClient;
  12use bedrock::bedrock_client::config::timeout::TimeoutConfig;
  13use bedrock::bedrock_client::types::{
  14    CachePointBlock, CachePointType, ContentBlockDelta, ContentBlockStart, ConverseStreamOutput,
  15    ReasoningContentBlockDelta, StopReason,
  16};
  17use bedrock::{
  18    BedrockAnyToolChoice, BedrockAutoToolChoice, BedrockBlob, BedrockError, BedrockInnerContent,
  19    BedrockMessage, BedrockModelMode, BedrockStreamingResponse, BedrockThinkingBlock,
  20    BedrockThinkingTextBlock, BedrockTool, BedrockToolChoice, BedrockToolConfig,
  21    BedrockToolInputSchema, BedrockToolResultBlock, BedrockToolResultContentBlock,
  22    BedrockToolResultStatus, BedrockToolSpec, BedrockToolUseBlock, Model, value_to_aws_document,
  23};
  24use collections::{BTreeMap, HashMap};
  25use credentials_provider::CredentialsProvider;
  26use editor::{Editor, EditorElement, EditorStyle};
  27use futures::{FutureExt, Stream, StreamExt, future::BoxFuture, stream::BoxStream};
  28use gpui::{
  29    AnyView, App, AsyncApp, Context, Entity, FontStyle, FontWeight, Subscription, Task, TextStyle,
  30    WhiteSpace,
  31};
  32use gpui_tokio::Tokio;
  33use http_client::HttpClient;
  34use language_model::{
  35    AuthenticateError, LanguageModel, LanguageModelCacheConfiguration,
  36    LanguageModelCompletionError, LanguageModelCompletionEvent, LanguageModelId, LanguageModelName,
  37    LanguageModelProvider, LanguageModelProviderId, LanguageModelProviderName,
  38    LanguageModelProviderState, LanguageModelRequest, LanguageModelToolChoice,
  39    LanguageModelToolResultContent, LanguageModelToolUse, MessageContent, RateLimiter, Role,
  40    TokenUsage,
  41};
  42use schemars::JsonSchema;
  43use serde::{Deserialize, Serialize};
  44use serde_json::Value;
  45use settings::{Settings, SettingsStore};
  46use smol::lock::OnceCell;
  47use strum::{EnumIter, IntoEnumIterator, IntoStaticStr};
  48use theme::ThemeSettings;
  49use ui::{Icon, IconName, List, Tooltip, prelude::*};
  50use util::ResultExt;
  51
  52use crate::AllLanguageModelSettings;
  53
  54const PROVIDER_ID: LanguageModelProviderId = LanguageModelProviderId::new("amazon-bedrock");
  55const PROVIDER_NAME: LanguageModelProviderName = LanguageModelProviderName::new("Amazon Bedrock");
  56
  57#[derive(Default, Clone, Deserialize, Serialize, PartialEq, Debug)]
  58pub struct BedrockCredentials {
  59    pub access_key_id: String,
  60    pub secret_access_key: String,
  61    pub session_token: Option<String>,
  62    pub region: String,
  63}
  64
  65#[derive(Default, Clone, Debug, PartialEq)]
  66pub struct AmazonBedrockSettings {
  67    pub available_models: Vec<AvailableModel>,
  68    pub region: Option<String>,
  69    pub endpoint: Option<String>,
  70    pub profile_name: Option<String>,
  71    pub role_arn: Option<String>,
  72    pub authentication_method: Option<BedrockAuthMethod>,
  73}
  74
  75#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumIter, IntoStaticStr, JsonSchema)]
  76pub enum BedrockAuthMethod {
  77    #[serde(rename = "named_profile")]
  78    NamedProfile,
  79    #[serde(rename = "sso")]
  80    SingleSignOn,
  81    /// IMDSv2, PodIdentity, env vars, etc.
  82    #[serde(rename = "default")]
  83    Automatic,
  84}
  85
  86#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
  87pub struct AvailableModel {
  88    pub name: String,
  89    pub display_name: Option<String>,
  90    pub max_tokens: u64,
  91    pub cache_configuration: Option<LanguageModelCacheConfiguration>,
  92    pub max_output_tokens: Option<u64>,
  93    pub default_temperature: Option<f32>,
  94    pub mode: Option<ModelMode>,
  95}
  96
  97#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
  98#[serde(tag = "type", rename_all = "lowercase")]
  99pub enum ModelMode {
 100    #[default]
 101    Default,
 102    Thinking {
 103        /// The maximum number of tokens to use for reasoning. Must be lower than the model's `max_output_tokens`.
 104        budget_tokens: Option<u64>,
 105    },
 106}
 107
 108impl From<ModelMode> for BedrockModelMode {
 109    fn from(value: ModelMode) -> Self {
 110        match value {
 111            ModelMode::Default => BedrockModelMode::Default,
 112            ModelMode::Thinking { budget_tokens } => BedrockModelMode::Thinking { budget_tokens },
 113        }
 114    }
 115}
 116
 117impl From<BedrockModelMode> for ModelMode {
 118    fn from(value: BedrockModelMode) -> Self {
 119        match value {
 120            BedrockModelMode::Default => ModelMode::Default,
 121            BedrockModelMode::Thinking { budget_tokens } => ModelMode::Thinking { budget_tokens },
 122        }
 123    }
 124}
 125
 126/// The URL of the base AWS service.
 127///
 128/// Right now we're just using this as the key to store the AWS credentials
 129/// under in the keychain.
 130const AMAZON_AWS_URL: &str = "https://amazonaws.com";
 131
 132// These environment variables all use a `ZED_` prefix because we don't want to overwrite the user's AWS credentials.
 133const ZED_BEDROCK_ACCESS_KEY_ID_VAR: &str = "ZED_ACCESS_KEY_ID";
 134const ZED_BEDROCK_SECRET_ACCESS_KEY_VAR: &str = "ZED_SECRET_ACCESS_KEY";
 135const ZED_BEDROCK_SESSION_TOKEN_VAR: &str = "ZED_SESSION_TOKEN";
 136const ZED_AWS_PROFILE_VAR: &str = "ZED_AWS_PROFILE";
 137const ZED_BEDROCK_REGION_VAR: &str = "ZED_AWS_REGION";
 138const ZED_AWS_CREDENTIALS_VAR: &str = "ZED_AWS_CREDENTIALS";
 139const ZED_AWS_ENDPOINT_VAR: &str = "ZED_AWS_ENDPOINT";
 140
 141pub struct State {
 142    credentials: Option<BedrockCredentials>,
 143    settings: Option<AmazonBedrockSettings>,
 144    credentials_from_env: bool,
 145    _subscription: Subscription,
 146}
 147
 148impl State {
 149    fn reset_credentials(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 150        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 151        cx.spawn(async move |this, cx| {
 152            credentials_provider
 153                .delete_credentials(AMAZON_AWS_URL, cx)
 154                .await
 155                .log_err();
 156            this.update(cx, |this, cx| {
 157                this.credentials = None;
 158                this.credentials_from_env = false;
 159                this.settings = None;
 160                cx.notify();
 161            })
 162        })
 163    }
 164
 165    fn set_credentials(
 166        &mut self,
 167        credentials: BedrockCredentials,
 168        cx: &mut Context<Self>,
 169    ) -> Task<Result<()>> {
 170        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 171        cx.spawn(async move |this, cx| {
 172            credentials_provider
 173                .write_credentials(
 174                    AMAZON_AWS_URL,
 175                    "Bearer",
 176                    &serde_json::to_vec(&credentials)?,
 177                    cx,
 178                )
 179                .await?;
 180            this.update(cx, |this, cx| {
 181                this.credentials = Some(credentials);
 182                cx.notify();
 183            })
 184        })
 185    }
 186
 187    fn is_authenticated(&self) -> bool {
 188        let derived = self
 189            .settings
 190            .as_ref()
 191            .and_then(|s| s.authentication_method.as_ref());
 192        let creds = self.credentials.as_ref();
 193
 194        derived.is_some() || creds.is_some()
 195    }
 196
 197    fn authenticate(&self, cx: &mut Context<Self>) -> Task<Result<(), AuthenticateError>> {
 198        if self.is_authenticated() {
 199            return Task::ready(Ok(()));
 200        }
 201
 202        let credentials_provider = <dyn CredentialsProvider>::global(cx);
 203        cx.spawn(async move |this, cx| {
 204            let (credentials, from_env) =
 205                if let Ok(credentials) = std::env::var(ZED_AWS_CREDENTIALS_VAR) {
 206                    (credentials, true)
 207                } else {
 208                    let (_, credentials) = credentials_provider
 209                        .read_credentials(AMAZON_AWS_URL, cx)
 210                        .await?
 211                        .ok_or_else(|| AuthenticateError::CredentialsNotFound)?;
 212                    (
 213                        String::from_utf8(credentials)
 214                            .context("invalid {PROVIDER_NAME} credentials")?,
 215                        false,
 216                    )
 217                };
 218
 219            let credentials: BedrockCredentials =
 220                serde_json::from_str(&credentials).context("failed to parse credentials")?;
 221
 222            this.update(cx, |this, cx| {
 223                this.credentials = Some(credentials);
 224                this.credentials_from_env = from_env;
 225                cx.notify();
 226            })?;
 227
 228            Ok(())
 229        })
 230    }
 231
 232    fn get_region(&self) -> String {
 233        // Get region - from credentials or directly from settings
 234        let credentials_region = self.credentials.as_ref().map(|s| s.region.clone());
 235        let settings_region = self.settings.as_ref().and_then(|s| s.region.clone());
 236
 237        // Use credentials region if available, otherwise use settings region, finally fall back to default
 238        credentials_region
 239            .or(settings_region)
 240            .unwrap_or(String::from("us-east-1"))
 241    }
 242}
 243
 244pub struct BedrockLanguageModelProvider {
 245    http_client: AwsHttpClient,
 246    handle: tokio::runtime::Handle,
 247    state: gpui::Entity<State>,
 248}
 249
 250impl BedrockLanguageModelProvider {
 251    pub fn new(http_client: Arc<dyn HttpClient>, cx: &mut App) -> Self {
 252        let state = cx.new(|cx| State {
 253            credentials: None,
 254            settings: Some(AllLanguageModelSettings::get_global(cx).bedrock.clone()),
 255            credentials_from_env: false,
 256            _subscription: cx.observe_global::<SettingsStore>(|_, cx| {
 257                cx.notify();
 258            }),
 259        });
 260
 261        Self {
 262            http_client: AwsHttpClient::new(http_client.clone()),
 263            handle: Tokio::handle(cx),
 264            state,
 265        }
 266    }
 267
 268    fn create_language_model(&self, model: bedrock::Model) -> Arc<dyn LanguageModel> {
 269        Arc::new(BedrockModel {
 270            id: LanguageModelId::from(model.id().to_string()),
 271            model,
 272            http_client: self.http_client.clone(),
 273            handle: self.handle.clone(),
 274            state: self.state.clone(),
 275            client: OnceCell::new(),
 276            request_limiter: RateLimiter::new(4),
 277        })
 278    }
 279}
 280
 281impl LanguageModelProvider for BedrockLanguageModelProvider {
 282    fn id(&self) -> LanguageModelProviderId {
 283        PROVIDER_ID
 284    }
 285
 286    fn name(&self) -> LanguageModelProviderName {
 287        PROVIDER_NAME
 288    }
 289
 290    fn icon(&self) -> IconName {
 291        IconName::AiBedrock
 292    }
 293
 294    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
 295        Some(self.create_language_model(bedrock::Model::default()))
 296    }
 297
 298    fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
 299        let region = self.state.read(cx).get_region();
 300        Some(self.create_language_model(bedrock::Model::default_fast(region.as_str())))
 301    }
 302
 303    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
 304        let mut models = BTreeMap::default();
 305
 306        for model in bedrock::Model::iter() {
 307            if !matches!(model, bedrock::Model::Custom { .. }) {
 308                // TODO: Sonnet 3.7 vs. 3.7 Thinking bug is here.
 309                models.insert(model.id().to_string(), model);
 310            }
 311        }
 312
 313        // Override with available models from settings
 314        for model in AllLanguageModelSettings::get_global(cx)
 315            .bedrock
 316            .available_models
 317            .iter()
 318        {
 319            models.insert(
 320                model.name.clone(),
 321                bedrock::Model::Custom {
 322                    name: model.name.clone(),
 323                    display_name: model.display_name.clone(),
 324                    max_tokens: model.max_tokens,
 325                    max_output_tokens: model.max_output_tokens,
 326                    default_temperature: model.default_temperature,
 327                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
 328                        bedrock::BedrockModelCacheConfiguration {
 329                            max_cache_anchors: config.max_cache_anchors,
 330                            min_total_token: config.min_total_token,
 331                        }
 332                    }),
 333                },
 334            );
 335        }
 336
 337        models
 338            .into_values()
 339            .map(|model| self.create_language_model(model))
 340            .collect()
 341    }
 342
 343    fn is_authenticated(&self, cx: &App) -> bool {
 344        self.state.read(cx).is_authenticated()
 345    }
 346
 347    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
 348        self.state.update(cx, |state, cx| state.authenticate(cx))
 349    }
 350
 351    fn configuration_view(
 352        &self,
 353        _target_agent: language_model::ConfigurationViewTargetAgent,
 354        window: &mut Window,
 355        cx: &mut App,
 356    ) -> AnyView {
 357        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
 358            .into()
 359    }
 360
 361    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
 362        self.state
 363            .update(cx, |state, cx| state.reset_credentials(cx))
 364    }
 365}
 366
 367impl LanguageModelProviderState for BedrockLanguageModelProvider {
 368    type ObservableEntity = State;
 369
 370    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
 371        Some(self.state.clone())
 372    }
 373}
 374
 375struct BedrockModel {
 376    id: LanguageModelId,
 377    model: Model,
 378    http_client: AwsHttpClient,
 379    handle: tokio::runtime::Handle,
 380    client: OnceCell<BedrockClient>,
 381    state: gpui::Entity<State>,
 382    request_limiter: RateLimiter,
 383}
 384
 385impl BedrockModel {
 386    fn get_or_init_client(&self, cx: &AsyncApp) -> anyhow::Result<&BedrockClient> {
 387        self.client
 388            .get_or_try_init_blocking(|| {
 389                let (auth_method, credentials, endpoint, region, settings) =
 390                    cx.read_entity(&self.state, |state, _cx| {
 391                        let auth_method = state
 392                            .settings
 393                            .as_ref()
 394                            .and_then(|s| s.authentication_method.clone());
 395
 396                        let endpoint = state.settings.as_ref().and_then(|s| s.endpoint.clone());
 397
 398                        let region = state.get_region();
 399
 400                        (
 401                            auth_method,
 402                            state.credentials.clone(),
 403                            endpoint,
 404                            region,
 405                            state.settings.clone(),
 406                        )
 407                    })?;
 408
 409                let mut config_builder = aws_config::defaults(BehaviorVersion::latest())
 410                    .stalled_stream_protection(StalledStreamProtectionConfig::disabled())
 411                    .http_client(self.http_client.clone())
 412                    .region(Region::new(region))
 413                    .timeout_config(TimeoutConfig::disabled());
 414
 415                if let Some(endpoint_url) = endpoint
 416                    && !endpoint_url.is_empty() {
 417                        config_builder = config_builder.endpoint_url(endpoint_url);
 418                    }
 419
 420                match auth_method {
 421                    None => {
 422                        if let Some(creds) = credentials {
 423                            let aws_creds = Credentials::new(
 424                                creds.access_key_id,
 425                                creds.secret_access_key,
 426                                creds.session_token,
 427                                None,
 428                                "zed-bedrock-provider",
 429                            );
 430                            config_builder = config_builder.credentials_provider(aws_creds);
 431                        }
 432                    }
 433                    Some(BedrockAuthMethod::NamedProfile)
 434                    | Some(BedrockAuthMethod::SingleSignOn) => {
 435                        // Currently NamedProfile and SSO behave the same way but only the instructions change
 436                        // Until we support BearerAuth through SSO, this will not change.
 437                        let profile_name = settings
 438                            .and_then(|s| s.profile_name)
 439                            .unwrap_or_else(|| "default".to_string());
 440
 441                        if !profile_name.is_empty() {
 442                            config_builder = config_builder.profile_name(profile_name);
 443                        }
 444                    }
 445                    Some(BedrockAuthMethod::Automatic) => {
 446                        // Use default credential provider chain
 447                    }
 448                }
 449
 450                let config = self.handle.block_on(config_builder.load());
 451                anyhow::Ok(BedrockClient::new(&config))
 452            })
 453            .context("initializing Bedrock client")?;
 454
 455        self.client.get().context("Bedrock client not initialized")
 456    }
 457
 458    fn stream_completion(
 459        &self,
 460        request: bedrock::Request,
 461        cx: &AsyncApp,
 462    ) -> BoxFuture<
 463        'static,
 464        Result<BoxStream<'static, Result<BedrockStreamingResponse, BedrockError>>>,
 465    > {
 466        let Ok(runtime_client) = self
 467            .get_or_init_client(cx)
 468            .cloned()
 469            .context("Bedrock client not initialized")
 470        else {
 471            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
 472        };
 473
 474        match Tokio::spawn(cx, bedrock::stream_completion(runtime_client, request)) {
 475            Ok(res) => async { res.await.map_err(|err| anyhow!(err))? }.boxed(),
 476            Err(err) => futures::future::ready(Err(anyhow!(err))).boxed(),
 477        }
 478    }
 479}
 480
 481impl LanguageModel for BedrockModel {
 482    fn id(&self) -> LanguageModelId {
 483        self.id.clone()
 484    }
 485
 486    fn name(&self) -> LanguageModelName {
 487        LanguageModelName::from(self.model.display_name().to_string())
 488    }
 489
 490    fn provider_id(&self) -> LanguageModelProviderId {
 491        PROVIDER_ID
 492    }
 493
 494    fn provider_name(&self) -> LanguageModelProviderName {
 495        PROVIDER_NAME
 496    }
 497
 498    fn supports_tools(&self) -> bool {
 499        self.model.supports_tool_use()
 500    }
 501
 502    fn supports_images(&self) -> bool {
 503        false
 504    }
 505
 506    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
 507        match choice {
 508            LanguageModelToolChoice::Auto | LanguageModelToolChoice::Any => {
 509                self.model.supports_tool_use()
 510            }
 511            // Add support for None - we'll filter tool calls at response
 512            LanguageModelToolChoice::None => self.model.supports_tool_use(),
 513        }
 514    }
 515
 516    fn telemetry_id(&self) -> String {
 517        format!("bedrock/{}", self.model.id())
 518    }
 519
 520    fn max_token_count(&self) -> u64 {
 521        self.model.max_token_count()
 522    }
 523
 524    fn max_output_tokens(&self) -> Option<u64> {
 525        Some(self.model.max_output_tokens())
 526    }
 527
 528    fn count_tokens(
 529        &self,
 530        request: LanguageModelRequest,
 531        cx: &App,
 532    ) -> BoxFuture<'static, Result<u64>> {
 533        get_bedrock_tokens(request, cx)
 534    }
 535
 536    fn stream_completion(
 537        &self,
 538        request: LanguageModelRequest,
 539        cx: &AsyncApp,
 540    ) -> BoxFuture<
 541        'static,
 542        Result<
 543            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 544            LanguageModelCompletionError,
 545        >,
 546    > {
 547        let Ok(region) = cx.read_entity(&self.state, |state, _cx| state.get_region()) else {
 548            return async move { Err(anyhow::anyhow!("App State Dropped").into()) }.boxed();
 549        };
 550
 551        let model_id = match self.model.cross_region_inference_id(&region) {
 552            Ok(s) => s,
 553            Err(e) => {
 554                return async move { Err(e.into()) }.boxed();
 555            }
 556        };
 557
 558        let deny_tool_calls = request.tool_choice == Some(LanguageModelToolChoice::None);
 559
 560        let request = match into_bedrock(
 561            request,
 562            model_id,
 563            self.model.default_temperature(),
 564            self.model.max_output_tokens(),
 565            self.model.mode(),
 566            self.model.supports_caching(),
 567        ) {
 568            Ok(request) => request,
 569            Err(err) => return futures::future::ready(Err(err.into())).boxed(),
 570        };
 571
 572        let request = self.stream_completion(request, cx);
 573        let future = self.request_limiter.stream(async move {
 574            let response = request.await.map_err(|err| anyhow!(err))?;
 575            let events = map_to_language_model_completion_events(response);
 576
 577            if deny_tool_calls {
 578                Ok(deny_tool_use_events(events).boxed())
 579            } else {
 580                Ok(events.boxed())
 581            }
 582        });
 583
 584        async move { Ok(future.await?.boxed()) }.boxed()
 585    }
 586
 587    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
 588        self.model
 589            .cache_configuration()
 590            .map(|config| LanguageModelCacheConfiguration {
 591                max_cache_anchors: config.max_cache_anchors,
 592                should_speculate: false,
 593                min_total_token: config.min_total_token,
 594            })
 595    }
 596}
 597
 598fn deny_tool_use_events(
 599    events: impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 600) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 601    events.map(|event| {
 602        match event {
 603            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 604                // Convert tool use to an error message if model decided to call it
 605                Ok(LanguageModelCompletionEvent::Text(format!(
 606                    "\n\n[Error: Tool calls are disabled in this context. Attempted to call '{}']",
 607                    tool_use.name
 608                )))
 609            }
 610            other => other,
 611        }
 612    })
 613}
 614
 615pub fn into_bedrock(
 616    request: LanguageModelRequest,
 617    model: String,
 618    default_temperature: f32,
 619    max_output_tokens: u64,
 620    mode: BedrockModelMode,
 621    supports_caching: bool,
 622) -> Result<bedrock::Request> {
 623    let mut new_messages: Vec<BedrockMessage> = Vec::new();
 624    let mut system_message = String::new();
 625
 626    for message in request.messages {
 627        if message.contents_empty() {
 628            continue;
 629        }
 630
 631        match message.role {
 632            Role::User | Role::Assistant => {
 633                let mut bedrock_message_content: Vec<BedrockInnerContent> = message
 634                    .content
 635                    .into_iter()
 636                    .filter_map(|content| match content {
 637                        MessageContent::Text(text) => {
 638                            if !text.is_empty() {
 639                                Some(BedrockInnerContent::Text(text))
 640                            } else {
 641                                None
 642                            }
 643                        }
 644                        MessageContent::Thinking { text, signature } => {
 645                            if model.contains(Model::DeepSeekR1.request_id()) {
 646                                // DeepSeekR1 doesn't support thinking blocks
 647                                // And the AWS API demands that you strip them
 648                                return None;
 649                            }
 650                            let thinking = BedrockThinkingTextBlock::builder()
 651                                .text(text)
 652                                .set_signature(signature)
 653                                .build()
 654                                .context("failed to build reasoning block")
 655                                .log_err()?;
 656
 657                            Some(BedrockInnerContent::ReasoningContent(
 658                                BedrockThinkingBlock::ReasoningText(thinking),
 659                            ))
 660                        }
 661                        MessageContent::RedactedThinking(blob) => {
 662                            if model.contains(Model::DeepSeekR1.request_id()) {
 663                                // DeepSeekR1 doesn't support thinking blocks
 664                                // And the AWS API demands that you strip them
 665                                return None;
 666                            }
 667                            let redacted =
 668                                BedrockThinkingBlock::RedactedContent(BedrockBlob::new(blob));
 669
 670                            Some(BedrockInnerContent::ReasoningContent(redacted))
 671                        }
 672                        MessageContent::ToolUse(tool_use) => {
 673                            let input = if tool_use.input.is_null() {
 674                                // Bedrock API requires valid JsonValue, not null, for tool use input
 675                                value_to_aws_document(&serde_json::json!({}))
 676                            } else {
 677                                value_to_aws_document(&tool_use.input)
 678                            };
 679                            BedrockToolUseBlock::builder()
 680                                .name(tool_use.name.to_string())
 681                                .tool_use_id(tool_use.id.to_string())
 682                                .input(input)
 683                                .build()
 684                                .context("failed to build Bedrock tool use block")
 685                                .log_err()
 686                                .map(BedrockInnerContent::ToolUse)
 687                        },
 688                        MessageContent::ToolResult(tool_result) => {
 689                            BedrockToolResultBlock::builder()
 690                                .tool_use_id(tool_result.tool_use_id.to_string())
 691                                .content(match tool_result.content {
 692                                    LanguageModelToolResultContent::Text(text) => {
 693                                        BedrockToolResultContentBlock::Text(text.to_string())
 694                                    }
 695                                    LanguageModelToolResultContent::Image(_) => {
 696                                        BedrockToolResultContentBlock::Text(
 697                                            // TODO: Bedrock image support
 698                                            "[Tool responded with an image, but Zed doesn't support these in Bedrock models yet]".to_string()
 699                                        )
 700                                    }
 701                                })
 702                                .status({
 703                                    if tool_result.is_error {
 704                                        BedrockToolResultStatus::Error
 705                                    } else {
 706                                        BedrockToolResultStatus::Success
 707                                    }
 708                                })
 709                                .build()
 710                                .context("failed to build Bedrock tool result block")
 711                                .log_err()
 712                                .map(BedrockInnerContent::ToolResult)
 713                        }
 714                        _ => None,
 715                    })
 716                    .collect();
 717                if message.cache && supports_caching {
 718                    bedrock_message_content.push(BedrockInnerContent::CachePoint(
 719                        CachePointBlock::builder()
 720                            .r#type(CachePointType::Default)
 721                            .build()
 722                            .context("failed to build cache point block")?,
 723                    ));
 724                }
 725                let bedrock_role = match message.role {
 726                    Role::User => bedrock::BedrockRole::User,
 727                    Role::Assistant => bedrock::BedrockRole::Assistant,
 728                    Role::System => unreachable!("System role should never occur here"),
 729                };
 730                if let Some(last_message) = new_messages.last_mut()
 731                    && last_message.role == bedrock_role {
 732                        last_message.content.extend(bedrock_message_content);
 733                        continue;
 734                    }
 735                new_messages.push(
 736                    BedrockMessage::builder()
 737                        .role(bedrock_role)
 738                        .set_content(Some(bedrock_message_content))
 739                        .build()
 740                        .context("failed to build Bedrock message")?,
 741                );
 742            }
 743            Role::System => {
 744                if !system_message.is_empty() {
 745                    system_message.push_str("\n\n");
 746                }
 747                system_message.push_str(&message.string_contents());
 748            }
 749        }
 750    }
 751
 752    let mut tool_spec: Vec<BedrockTool> = request
 753        .tools
 754        .iter()
 755        .filter_map(|tool| {
 756            Some(BedrockTool::ToolSpec(
 757                BedrockToolSpec::builder()
 758                    .name(tool.name.clone())
 759                    .description(tool.description.clone())
 760                    .input_schema(BedrockToolInputSchema::Json(value_to_aws_document(
 761                        &tool.input_schema,
 762                    )))
 763                    .build()
 764                    .log_err()?,
 765            ))
 766        })
 767        .collect();
 768
 769    if !tool_spec.is_empty() && supports_caching {
 770        tool_spec.push(BedrockTool::CachePoint(
 771            CachePointBlock::builder()
 772                .r#type(CachePointType::Default)
 773                .build()
 774                .context("failed to build cache point block")?,
 775        ));
 776    }
 777
 778    let tool_choice = match request.tool_choice {
 779        Some(LanguageModelToolChoice::Auto) | None => {
 780            BedrockToolChoice::Auto(BedrockAutoToolChoice::builder().build())
 781        }
 782        Some(LanguageModelToolChoice::Any) => {
 783            BedrockToolChoice::Any(BedrockAnyToolChoice::builder().build())
 784        }
 785        Some(LanguageModelToolChoice::None) => {
 786            // For None, we still use Auto but will filter out tool calls in the response
 787            BedrockToolChoice::Auto(BedrockAutoToolChoice::builder().build())
 788        }
 789    };
 790    let tool_config: BedrockToolConfig = BedrockToolConfig::builder()
 791        .set_tools(Some(tool_spec))
 792        .tool_choice(tool_choice)
 793        .build()?;
 794
 795    Ok(bedrock::Request {
 796        model,
 797        messages: new_messages,
 798        max_tokens: max_output_tokens,
 799        system: Some(system_message),
 800        tools: Some(tool_config),
 801        thinking: if request.thinking_allowed
 802            && let BedrockModelMode::Thinking { budget_tokens } = mode
 803        {
 804            Some(bedrock::Thinking::Enabled { budget_tokens })
 805        } else {
 806            None
 807        },
 808        metadata: None,
 809        stop_sequences: Vec::new(),
 810        temperature: request.temperature.or(Some(default_temperature)),
 811        top_k: None,
 812        top_p: None,
 813    })
 814}
 815
 816// TODO: just call the ConverseOutput.usage() method:
 817// https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/operation/converse/struct.ConverseOutput.html#method.output
 818pub fn get_bedrock_tokens(
 819    request: LanguageModelRequest,
 820    cx: &App,
 821) -> BoxFuture<'static, Result<u64>> {
 822    cx.background_executor()
 823        .spawn(async move {
 824            let messages = request.messages;
 825            let mut tokens_from_images = 0;
 826            let mut string_messages = Vec::with_capacity(messages.len());
 827
 828            for message in messages {
 829                use language_model::MessageContent;
 830
 831                let mut string_contents = String::new();
 832
 833                for content in message.content {
 834                    match content {
 835                        MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
 836                            string_contents.push_str(&text);
 837                        }
 838                        MessageContent::RedactedThinking(_) => {}
 839                        MessageContent::Image(image) => {
 840                            tokens_from_images += image.estimate_tokens();
 841                        }
 842                        MessageContent::ToolUse(_tool_use) => {
 843                            // TODO: Estimate token usage from tool uses.
 844                        }
 845                        MessageContent::ToolResult(tool_result) => match tool_result.content {
 846                            LanguageModelToolResultContent::Text(text) => {
 847                                string_contents.push_str(&text);
 848                            }
 849                            LanguageModelToolResultContent::Image(image) => {
 850                                tokens_from_images += image.estimate_tokens();
 851                            }
 852                        },
 853                    }
 854                }
 855
 856                if !string_contents.is_empty() {
 857                    string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
 858                        role: match message.role {
 859                            Role::User => "user".into(),
 860                            Role::Assistant => "assistant".into(),
 861                            Role::System => "system".into(),
 862                        },
 863                        content: Some(string_contents),
 864                        name: None,
 865                        function_call: None,
 866                    });
 867                }
 868            }
 869
 870            // Tiktoken doesn't yet support these models, so we manually use the
 871            // same tokenizer as GPT-4.
 872            tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
 873                .map(|tokens| (tokens + tokens_from_images) as u64)
 874        })
 875        .boxed()
 876}
 877
 878pub fn map_to_language_model_completion_events(
 879    events: Pin<Box<dyn Send + Stream<Item = Result<BedrockStreamingResponse, BedrockError>>>>,
 880) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 881    struct RawToolUse {
 882        id: String,
 883        name: String,
 884        input_json: String,
 885    }
 886
 887    struct State {
 888        events: Pin<Box<dyn Send + Stream<Item = Result<BedrockStreamingResponse, BedrockError>>>>,
 889        tool_uses_by_index: HashMap<i32, RawToolUse>,
 890    }
 891
 892    let initial_state = State {
 893        events,
 894        tool_uses_by_index: HashMap::default(),
 895    };
 896
 897    futures::stream::unfold(initial_state, |mut state| async move {
 898        match state.events.next().await {
 899            Some(event_result) => match event_result {
 900                Ok(event) => {
 901                    let result = match event {
 902                        ConverseStreamOutput::ContentBlockDelta(cb_delta) => match cb_delta.delta {
 903                            Some(ContentBlockDelta::Text(text)) => {
 904                                Some(Ok(LanguageModelCompletionEvent::Text(text)))
 905                            }
 906                            Some(ContentBlockDelta::ToolUse(tool_output)) => {
 907                                if let Some(tool_use) = state
 908                                    .tool_uses_by_index
 909                                    .get_mut(&cb_delta.content_block_index)
 910                                {
 911                                    tool_use.input_json.push_str(tool_output.input());
 912                                }
 913                                None
 914                            }
 915                            Some(ContentBlockDelta::ReasoningContent(thinking)) => match thinking {
 916                                ReasoningContentBlockDelta::Text(thoughts) => {
 917                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 918                                        text: thoughts.clone(),
 919                                        signature: None,
 920                                    }))
 921                                }
 922                                ReasoningContentBlockDelta::Signature(sig) => {
 923                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 924                                        text: "".into(),
 925                                        signature: Some(sig),
 926                                    }))
 927                                }
 928                                ReasoningContentBlockDelta::RedactedContent(redacted) => {
 929                                    let content = String::from_utf8(redacted.into_inner())
 930                                        .unwrap_or("REDACTED".to_string());
 931                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 932                                        text: content,
 933                                        signature: None,
 934                                    }))
 935                                }
 936                                _ => None,
 937                            },
 938                            _ => None,
 939                        },
 940                        ConverseStreamOutput::ContentBlockStart(cb_start) => {
 941                            if let Some(ContentBlockStart::ToolUse(tool_start)) = cb_start.start {
 942                                state.tool_uses_by_index.insert(
 943                                    cb_start.content_block_index,
 944                                    RawToolUse {
 945                                        id: tool_start.tool_use_id,
 946                                        name: tool_start.name,
 947                                        input_json: String::new(),
 948                                    },
 949                                );
 950                            }
 951                            None
 952                        }
 953                        ConverseStreamOutput::ContentBlockStop(cb_stop) => state
 954                            .tool_uses_by_index
 955                            .remove(&cb_stop.content_block_index)
 956                            .map(|tool_use| {
 957                                let input = if tool_use.input_json.is_empty() {
 958                                    Value::Null
 959                                } else {
 960                                    serde_json::Value::from_str(&tool_use.input_json)
 961                                        .unwrap_or(Value::Null)
 962                                };
 963
 964                                Ok(LanguageModelCompletionEvent::ToolUse(
 965                                    LanguageModelToolUse {
 966                                        id: tool_use.id.into(),
 967                                        name: tool_use.name.into(),
 968                                        is_input_complete: true,
 969                                        raw_input: tool_use.input_json.clone(),
 970                                        input,
 971                                    },
 972                                ))
 973                            }),
 974                        ConverseStreamOutput::Metadata(cb_meta) => cb_meta.usage.map(|metadata| {
 975                            Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
 976                                input_tokens: metadata.input_tokens as u64,
 977                                output_tokens: metadata.output_tokens as u64,
 978                                cache_creation_input_tokens: metadata
 979                                    .cache_write_input_tokens
 980                                    .unwrap_or_default()
 981                                    as u64,
 982                                cache_read_input_tokens: metadata
 983                                    .cache_read_input_tokens
 984                                    .unwrap_or_default()
 985                                    as u64,
 986                            }))
 987                        }),
 988                        ConverseStreamOutput::MessageStop(message_stop) => {
 989                            let stop_reason = match message_stop.stop_reason {
 990                                StopReason::ToolUse => language_model::StopReason::ToolUse,
 991                                _ => language_model::StopReason::EndTurn,
 992                            };
 993                            Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason)))
 994                        }
 995                        _ => None,
 996                    };
 997
 998                    Some((result, state))
 999                }
1000                Err(err) => Some((
1001                    Some(Err(LanguageModelCompletionError::Other(anyhow!(err)))),
1002                    state,
1003                )),
1004            },
1005            None => None,
1006        }
1007    })
1008    .filter_map(|result| async move { result })
1009}
1010
1011struct ConfigurationView {
1012    access_key_id_editor: Entity<Editor>,
1013    secret_access_key_editor: Entity<Editor>,
1014    session_token_editor: Entity<Editor>,
1015    region_editor: Entity<Editor>,
1016    state: gpui::Entity<State>,
1017    load_credentials_task: Option<Task<()>>,
1018}
1019
1020impl ConfigurationView {
1021    const PLACEHOLDER_ACCESS_KEY_ID_TEXT: &'static str = "XXXXXXXXXXXXXXXX";
1022    const PLACEHOLDER_SECRET_ACCESS_KEY_TEXT: &'static str =
1023        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1024    const PLACEHOLDER_SESSION_TOKEN_TEXT: &'static str = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1025    const PLACEHOLDER_REGION: &'static str = "us-east-1";
1026
1027    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1028        cx.observe(&state, |_, _, cx| {
1029            cx.notify();
1030        })
1031        .detach();
1032
1033        let load_credentials_task = Some(cx.spawn({
1034            let state = state.clone();
1035            async move |this, cx| {
1036                if let Some(task) = state
1037                    .update(cx, |state, cx| state.authenticate(cx))
1038                    .log_err()
1039                {
1040                    // We don't log an error, because "not signed in" is also an error.
1041                    let _ = task.await;
1042                }
1043                this.update(cx, |this, cx| {
1044                    this.load_credentials_task = None;
1045                    cx.notify();
1046                })
1047                .log_err();
1048            }
1049        }));
1050
1051        Self {
1052            access_key_id_editor: cx.new(|cx| {
1053                let mut editor = Editor::single_line(window, cx);
1054                editor.set_placeholder_text(Self::PLACEHOLDER_ACCESS_KEY_ID_TEXT, cx);
1055                editor
1056            }),
1057            secret_access_key_editor: cx.new(|cx| {
1058                let mut editor = Editor::single_line(window, cx);
1059                editor.set_placeholder_text(Self::PLACEHOLDER_SECRET_ACCESS_KEY_TEXT, cx);
1060                editor
1061            }),
1062            session_token_editor: cx.new(|cx| {
1063                let mut editor = Editor::single_line(window, cx);
1064                editor.set_placeholder_text(Self::PLACEHOLDER_SESSION_TOKEN_TEXT, cx);
1065                editor
1066            }),
1067            region_editor: cx.new(|cx| {
1068                let mut editor = Editor::single_line(window, cx);
1069                editor.set_placeholder_text(Self::PLACEHOLDER_REGION, cx);
1070                editor
1071            }),
1072            state,
1073            load_credentials_task,
1074        }
1075    }
1076
1077    fn save_credentials(
1078        &mut self,
1079        _: &menu::Confirm,
1080        _window: &mut Window,
1081        cx: &mut Context<Self>,
1082    ) {
1083        let access_key_id = self
1084            .access_key_id_editor
1085            .read(cx)
1086            .text(cx)
1087            .to_string()
1088            .trim()
1089            .to_string();
1090        let secret_access_key = self
1091            .secret_access_key_editor
1092            .read(cx)
1093            .text(cx)
1094            .to_string()
1095            .trim()
1096            .to_string();
1097        let session_token = self
1098            .session_token_editor
1099            .read(cx)
1100            .text(cx)
1101            .to_string()
1102            .trim()
1103            .to_string();
1104        let session_token = if session_token.is_empty() {
1105            None
1106        } else {
1107            Some(session_token)
1108        };
1109        let region = self
1110            .region_editor
1111            .read(cx)
1112            .text(cx)
1113            .to_string()
1114            .trim()
1115            .to_string();
1116        let region = if region.is_empty() {
1117            "us-east-1".to_string()
1118        } else {
1119            region
1120        };
1121
1122        let state = self.state.clone();
1123        cx.spawn(async move |_, cx| {
1124            state
1125                .update(cx, |state, cx| {
1126                    let credentials: BedrockCredentials = BedrockCredentials {
1127                        region: region.clone(),
1128                        access_key_id: access_key_id.clone(),
1129                        secret_access_key: secret_access_key.clone(),
1130                        session_token: session_token.clone(),
1131                    };
1132
1133                    state.set_credentials(credentials, cx)
1134                })?
1135                .await
1136        })
1137        .detach_and_log_err(cx);
1138    }
1139
1140    fn reset_credentials(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1141        self.access_key_id_editor
1142            .update(cx, |editor, cx| editor.set_text("", window, cx));
1143        self.secret_access_key_editor
1144            .update(cx, |editor, cx| editor.set_text("", window, cx));
1145        self.session_token_editor
1146            .update(cx, |editor, cx| editor.set_text("", window, cx));
1147        self.region_editor
1148            .update(cx, |editor, cx| editor.set_text("", window, cx));
1149
1150        let state = self.state.clone();
1151        cx.spawn(async move |_, cx| {
1152            state
1153                .update(cx, |state, cx| state.reset_credentials(cx))?
1154                .await
1155        })
1156        .detach_and_log_err(cx);
1157    }
1158
1159    fn make_text_style(&self, cx: &Context<Self>) -> TextStyle {
1160        let settings = ThemeSettings::get_global(cx);
1161        TextStyle {
1162            color: cx.theme().colors().text,
1163            font_family: settings.ui_font.family.clone(),
1164            font_features: settings.ui_font.features.clone(),
1165            font_fallbacks: settings.ui_font.fallbacks.clone(),
1166            font_size: rems(0.875).into(),
1167            font_weight: settings.ui_font.weight,
1168            font_style: FontStyle::Normal,
1169            line_height: relative(1.3),
1170            background_color: None,
1171            underline: None,
1172            strikethrough: None,
1173            white_space: WhiteSpace::Normal,
1174            text_overflow: None,
1175            text_align: Default::default(),
1176            line_clamp: None,
1177        }
1178    }
1179
1180    fn make_input_styles(&self, cx: &Context<Self>) -> Div {
1181        let bg_color = cx.theme().colors().editor_background;
1182        let border_color = cx.theme().colors().border;
1183
1184        h_flex()
1185            .w_full()
1186            .px_2()
1187            .py_1()
1188            .bg(bg_color)
1189            .border_1()
1190            .border_color(border_color)
1191            .rounded_sm()
1192    }
1193
1194    fn should_render_editor(&self, cx: &Context<Self>) -> bool {
1195        self.state.read(cx).is_authenticated()
1196    }
1197}
1198
1199impl Render for ConfigurationView {
1200    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1201        let env_var_set = self.state.read(cx).credentials_from_env;
1202        let bedrock_settings = self.state.read(cx).settings.as_ref();
1203        let bedrock_method = bedrock_settings
1204            .as_ref()
1205            .and_then(|s| s.authentication_method.clone());
1206
1207        if self.load_credentials_task.is_some() {
1208            return div().child(Label::new("Loading credentials...")).into_any();
1209        }
1210
1211        if self.should_render_editor(cx) {
1212            return h_flex()
1213                .mt_1()
1214                .p_1()
1215                .justify_between()
1216                .rounded_md()
1217                .border_1()
1218                .border_color(cx.theme().colors().border)
1219                .bg(cx.theme().colors().background)
1220                .child(
1221                    h_flex()
1222                        .gap_1()
1223                        .child(Icon::new(IconName::Check).color(Color::Success))
1224                        .child(Label::new(if env_var_set {
1225                            format!("Access Key ID is set in {ZED_BEDROCK_ACCESS_KEY_ID_VAR}, Secret Key is set in {ZED_BEDROCK_SECRET_ACCESS_KEY_VAR}, Region is set in {ZED_BEDROCK_REGION_VAR} environment variables.")
1226                        } else {
1227                            match bedrock_method {
1228                                Some(BedrockAuthMethod::Automatic) => "You are using automatic credentials".into(),
1229                                Some(BedrockAuthMethod::NamedProfile) => {
1230                                    "You are using named profile".into()
1231                                },
1232                                Some(BedrockAuthMethod::SingleSignOn) => "You are using a single sign on profile".into(),
1233                                None => "You are using static credentials".into(),
1234                            }
1235                        })),
1236                )
1237                .child(
1238                    Button::new("reset-key", "Reset Key")
1239                        .icon(Some(IconName::Trash))
1240                        .icon_size(IconSize::Small)
1241                        .icon_position(IconPosition::Start)
1242                        .disabled(env_var_set || bedrock_method.is_some())
1243                        .when(env_var_set, |this| {
1244                            this.tooltip(Tooltip::text(format!("To reset your credentials, unset the {ZED_BEDROCK_ACCESS_KEY_ID_VAR}, {ZED_BEDROCK_SECRET_ACCESS_KEY_VAR}, and {ZED_BEDROCK_REGION_VAR} environment variables.")))
1245                        })
1246                        .when(bedrock_method.is_some(), |this| {
1247                            this.tooltip(Tooltip::text("You cannot reset credentials as they're being derived, check Zed settings to understand how"))
1248                        })
1249                        .on_click(cx.listener(|this, _, window, cx| this.reset_credentials(window, cx))),
1250                )
1251                .into_any();
1252        }
1253
1254        v_flex()
1255            .size_full()
1256            .on_action(cx.listener(ConfigurationView::save_credentials))
1257            .child(Label::new("To use Zed's agent with Bedrock, you can set a custom authentication strategy through the settings.json, or use static credentials."))
1258            .child(Label::new("But, to access models on AWS, you need to:").mt_1())
1259            .child(
1260                List::new()
1261                    .child(
1262                        InstructionListItem::new(
1263                            "Grant permissions to the strategy you'll use according to the:",
1264                            Some("Prerequisites"),
1265                            Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
1266                        )
1267                    )
1268                    .child(
1269                        InstructionListItem::new(
1270                            "Select the models you would like access to:",
1271                            Some("Bedrock Model Catalog"),
1272                            Some("https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess"),
1273                        )
1274                    )
1275            )
1276            .child(self.render_static_credentials_ui(cx))
1277            .child(self.render_common_fields(cx))
1278            .child(
1279                Label::new(
1280                    format!("You can also assign the {ZED_BEDROCK_ACCESS_KEY_ID_VAR}, {ZED_BEDROCK_SECRET_ACCESS_KEY_VAR} AND {ZED_BEDROCK_REGION_VAR} environment variables and restart Zed."),
1281                )
1282                    .size(LabelSize::Small)
1283                    .color(Color::Muted)
1284                    .my_1(),
1285            )
1286            .child(
1287                Label::new(
1288                    format!("Optionally, if your environment uses AWS CLI profiles, you can set {ZED_AWS_PROFILE_VAR}; if it requires a custom endpoint, you can set {ZED_AWS_ENDPOINT_VAR}; and if it requires a Session Token, you can set {ZED_BEDROCK_SESSION_TOKEN_VAR}."),
1289                )
1290                    .size(LabelSize::Small)
1291                    .color(Color::Muted),
1292            )
1293            .into_any()
1294    }
1295}
1296
1297impl ConfigurationView {
1298    fn render_access_key_id_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1299        let text_style = self.make_text_style(cx);
1300
1301        EditorElement::new(
1302            &self.access_key_id_editor,
1303            EditorStyle {
1304                background: cx.theme().colors().editor_background,
1305                local_player: cx.theme().players().local(),
1306                text: text_style,
1307                ..Default::default()
1308            },
1309        )
1310    }
1311
1312    fn render_secret_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1313        let text_style = self.make_text_style(cx);
1314
1315        EditorElement::new(
1316            &self.secret_access_key_editor,
1317            EditorStyle {
1318                background: cx.theme().colors().editor_background,
1319                local_player: cx.theme().players().local(),
1320                text: text_style,
1321                ..Default::default()
1322            },
1323        )
1324    }
1325
1326    fn render_session_token_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1327        let text_style = self.make_text_style(cx);
1328
1329        EditorElement::new(
1330            &self.session_token_editor,
1331            EditorStyle {
1332                background: cx.theme().colors().editor_background,
1333                local_player: cx.theme().players().local(),
1334                text: text_style,
1335                ..Default::default()
1336            },
1337        )
1338    }
1339
1340    fn render_region_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1341        let text_style = self.make_text_style(cx);
1342
1343        EditorElement::new(
1344            &self.region_editor,
1345            EditorStyle {
1346                background: cx.theme().colors().editor_background,
1347                local_player: cx.theme().players().local(),
1348                text: text_style,
1349                ..Default::default()
1350            },
1351        )
1352    }
1353
1354    fn render_static_credentials_ui(&self, cx: &mut Context<Self>) -> AnyElement {
1355        v_flex()
1356            .my_2()
1357            .gap_1p5()
1358            .child(
1359                Label::new("Static Keys")
1360                    .size(LabelSize::Default)
1361                    .weight(FontWeight::BOLD),
1362            )
1363            .child(
1364                Label::new(
1365                    "This method uses your AWS access key ID and secret access key directly.",
1366                )
1367            )
1368            .child(
1369                List::new()
1370                    .child(InstructionListItem::new(
1371                        "Create an IAM user in the AWS console with programmatic access",
1372                        Some("IAM Console"),
1373                        Some("https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/users"),
1374                    ))
1375                    .child(InstructionListItem::new(
1376                        "Attach the necessary Bedrock permissions to this ",
1377                        Some("user"),
1378                        Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
1379                    ))
1380                    .child(InstructionListItem::text_only(
1381                        "Copy the access key ID and secret access key when provided",
1382                    ))
1383                    .child(InstructionListItem::text_only(
1384                        "Enter these credentials below",
1385                    )),
1386            )
1387            .child(
1388                v_flex()
1389                    .gap_0p5()
1390                    .child(Label::new("Access Key ID").size(LabelSize::Small))
1391                    .child(
1392                        self.make_input_styles(cx)
1393                            .child(self.render_access_key_id_editor(cx)),
1394                    ),
1395            )
1396            .child(
1397                v_flex()
1398                    .gap_0p5()
1399                    .child(Label::new("Secret Access Key").size(LabelSize::Small))
1400                    .child(self.make_input_styles(cx).child(self.render_secret_key_editor(cx))),
1401            )
1402            .child(
1403                v_flex()
1404                    .gap_0p5()
1405                    .child(Label::new("Session Token (Optional)").size(LabelSize::Small))
1406                    .child(
1407                        self.make_input_styles(cx)
1408                            .child(self.render_session_token_editor(cx)),
1409                    ),
1410            )
1411            .into_any_element()
1412    }
1413
1414    fn render_common_fields(&self, cx: &mut Context<Self>) -> AnyElement {
1415        v_flex()
1416            .gap_0p5()
1417            .child(Label::new("Region").size(LabelSize::Small))
1418            .child(
1419                self.make_input_styles(cx)
1420                    .child(self.render_region_editor(cx)),
1421            )
1422            .into_any_element()
1423    }
1424}