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(&self, window: &mut Window, cx: &mut App) -> AnyView {
 352        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
 353            .into()
 354    }
 355
 356    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
 357        self.state
 358            .update(cx, |state, cx| state.reset_credentials(cx))
 359    }
 360}
 361
 362impl LanguageModelProviderState for BedrockLanguageModelProvider {
 363    type ObservableEntity = State;
 364
 365    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
 366        Some(self.state.clone())
 367    }
 368}
 369
 370struct BedrockModel {
 371    id: LanguageModelId,
 372    model: Model,
 373    http_client: AwsHttpClient,
 374    handle: tokio::runtime::Handle,
 375    client: OnceCell<BedrockClient>,
 376    state: gpui::Entity<State>,
 377    request_limiter: RateLimiter,
 378}
 379
 380impl BedrockModel {
 381    fn get_or_init_client(&self, cx: &AsyncApp) -> anyhow::Result<&BedrockClient> {
 382        self.client
 383            .get_or_try_init_blocking(|| {
 384                let (auth_method, credentials, endpoint, region, settings) =
 385                    cx.read_entity(&self.state, |state, _cx| {
 386                        let auth_method = state
 387                            .settings
 388                            .as_ref()
 389                            .and_then(|s| s.authentication_method.clone());
 390
 391                        let endpoint = state.settings.as_ref().and_then(|s| s.endpoint.clone());
 392
 393                        let region = state.get_region();
 394
 395                        (
 396                            auth_method,
 397                            state.credentials.clone(),
 398                            endpoint,
 399                            region,
 400                            state.settings.clone(),
 401                        )
 402                    })?;
 403
 404                let mut config_builder = aws_config::defaults(BehaviorVersion::latest())
 405                    .stalled_stream_protection(StalledStreamProtectionConfig::disabled())
 406                    .http_client(self.http_client.clone())
 407                    .region(Region::new(region))
 408                    .timeout_config(TimeoutConfig::disabled());
 409
 410                if let Some(endpoint_url) = endpoint {
 411                    if !endpoint_url.is_empty() {
 412                        config_builder = config_builder.endpoint_url(endpoint_url);
 413                    }
 414                }
 415
 416                match auth_method {
 417                    None => {
 418                        if let Some(creds) = credentials {
 419                            let aws_creds = Credentials::new(
 420                                creds.access_key_id,
 421                                creds.secret_access_key,
 422                                creds.session_token,
 423                                None,
 424                                "zed-bedrock-provider",
 425                            );
 426                            config_builder = config_builder.credentials_provider(aws_creds);
 427                        }
 428                    }
 429                    Some(BedrockAuthMethod::NamedProfile)
 430                    | Some(BedrockAuthMethod::SingleSignOn) => {
 431                        // Currently NamedProfile and SSO behave the same way but only the instructions change
 432                        // Until we support BearerAuth through SSO, this will not change.
 433                        let profile_name = settings
 434                            .and_then(|s| s.profile_name)
 435                            .unwrap_or_else(|| "default".to_string());
 436
 437                        if !profile_name.is_empty() {
 438                            config_builder = config_builder.profile_name(profile_name);
 439                        }
 440                    }
 441                    Some(BedrockAuthMethod::Automatic) => {
 442                        // Use default credential provider chain
 443                    }
 444                }
 445
 446                let config = self.handle.block_on(config_builder.load());
 447                anyhow::Ok(BedrockClient::new(&config))
 448            })
 449            .context("initializing Bedrock client")?;
 450
 451        self.client.get().context("Bedrock client not initialized")
 452    }
 453
 454    fn stream_completion(
 455        &self,
 456        request: bedrock::Request,
 457        cx: &AsyncApp,
 458    ) -> BoxFuture<
 459        'static,
 460        Result<BoxStream<'static, Result<BedrockStreamingResponse, BedrockError>>>,
 461    > {
 462        let Ok(runtime_client) = self
 463            .get_or_init_client(&cx)
 464            .cloned()
 465            .context("Bedrock client not initialized")
 466        else {
 467            return futures::future::ready(Err(anyhow!("App state dropped"))).boxed();
 468        };
 469
 470        match Tokio::spawn(cx, bedrock::stream_completion(runtime_client, request)) {
 471            Ok(res) => async { res.await.map_err(|err| anyhow!(err))? }.boxed(),
 472            Err(err) => futures::future::ready(Err(anyhow!(err))).boxed(),
 473        }
 474    }
 475}
 476
 477impl LanguageModel for BedrockModel {
 478    fn id(&self) -> LanguageModelId {
 479        self.id.clone()
 480    }
 481
 482    fn name(&self) -> LanguageModelName {
 483        LanguageModelName::from(self.model.display_name().to_string())
 484    }
 485
 486    fn provider_id(&self) -> LanguageModelProviderId {
 487        PROVIDER_ID
 488    }
 489
 490    fn provider_name(&self) -> LanguageModelProviderName {
 491        PROVIDER_NAME
 492    }
 493
 494    fn supports_tools(&self) -> bool {
 495        self.model.supports_tool_use()
 496    }
 497
 498    fn supports_images(&self) -> bool {
 499        false
 500    }
 501
 502    fn supports_tool_choice(&self, choice: LanguageModelToolChoice) -> bool {
 503        match choice {
 504            LanguageModelToolChoice::Auto | LanguageModelToolChoice::Any => {
 505                self.model.supports_tool_use()
 506            }
 507            // Add support for None - we'll filter tool calls at response
 508            LanguageModelToolChoice::None => self.model.supports_tool_use(),
 509        }
 510    }
 511
 512    fn telemetry_id(&self) -> String {
 513        format!("bedrock/{}", self.model.id())
 514    }
 515
 516    fn max_token_count(&self) -> u64 {
 517        self.model.max_token_count()
 518    }
 519
 520    fn max_output_tokens(&self) -> Option<u64> {
 521        Some(self.model.max_output_tokens())
 522    }
 523
 524    fn count_tokens(
 525        &self,
 526        request: LanguageModelRequest,
 527        cx: &App,
 528    ) -> BoxFuture<'static, Result<u64>> {
 529        get_bedrock_tokens(request, cx)
 530    }
 531
 532    fn stream_completion(
 533        &self,
 534        request: LanguageModelRequest,
 535        cx: &AsyncApp,
 536    ) -> BoxFuture<
 537        'static,
 538        Result<
 539            BoxStream<'static, Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 540            LanguageModelCompletionError,
 541        >,
 542    > {
 543        let Ok(region) = cx.read_entity(&self.state, |state, _cx| state.get_region()) else {
 544            return async move { Err(anyhow::anyhow!("App State Dropped").into()) }.boxed();
 545        };
 546
 547        let model_id = match self.model.cross_region_inference_id(&region) {
 548            Ok(s) => s,
 549            Err(e) => {
 550                return async move { Err(e.into()) }.boxed();
 551            }
 552        };
 553
 554        let deny_tool_calls = request.tool_choice == Some(LanguageModelToolChoice::None);
 555
 556        let request = match into_bedrock(
 557            request,
 558            model_id,
 559            self.model.default_temperature(),
 560            self.model.max_output_tokens(),
 561            self.model.mode(),
 562            self.model.supports_caching(),
 563        ) {
 564            Ok(request) => request,
 565            Err(err) => return futures::future::ready(Err(err.into())).boxed(),
 566        };
 567
 568        let request = self.stream_completion(request, cx);
 569        let future = self.request_limiter.stream(async move {
 570            let response = request.await.map_err(|err| anyhow!(err))?;
 571            let events = map_to_language_model_completion_events(response);
 572
 573            if deny_tool_calls {
 574                Ok(deny_tool_use_events(events).boxed())
 575            } else {
 576                Ok(events.boxed())
 577            }
 578        });
 579
 580        async move { Ok(future.await?.boxed()) }.boxed()
 581    }
 582
 583    fn cache_configuration(&self) -> Option<LanguageModelCacheConfiguration> {
 584        self.model
 585            .cache_configuration()
 586            .map(|config| LanguageModelCacheConfiguration {
 587                max_cache_anchors: config.max_cache_anchors,
 588                should_speculate: false,
 589                min_total_token: config.min_total_token,
 590            })
 591    }
 592}
 593
 594fn deny_tool_use_events(
 595    events: impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>>,
 596) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 597    events.map(|event| {
 598        match event {
 599            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 600                // Convert tool use to an error message if model decided to call it
 601                Ok(LanguageModelCompletionEvent::Text(format!(
 602                    "\n\n[Error: Tool calls are disabled in this context. Attempted to call '{}']",
 603                    tool_use.name
 604                )))
 605            }
 606            other => other,
 607        }
 608    })
 609}
 610
 611pub fn into_bedrock(
 612    request: LanguageModelRequest,
 613    model: String,
 614    default_temperature: f32,
 615    max_output_tokens: u64,
 616    mode: BedrockModelMode,
 617    supports_caching: bool,
 618) -> Result<bedrock::Request> {
 619    let mut new_messages: Vec<BedrockMessage> = Vec::new();
 620    let mut system_message = String::new();
 621
 622    for message in request.messages {
 623        if message.contents_empty() {
 624            continue;
 625        }
 626
 627        match message.role {
 628            Role::User | Role::Assistant => {
 629                let mut bedrock_message_content: Vec<BedrockInnerContent> = message
 630                    .content
 631                    .into_iter()
 632                    .filter_map(|content| match content {
 633                        MessageContent::Text(text) => {
 634                            if !text.is_empty() {
 635                                Some(BedrockInnerContent::Text(text))
 636                            } else {
 637                                None
 638                            }
 639                        }
 640                        MessageContent::Thinking { text, signature } => {
 641                            if model.contains(Model::DeepSeekR1.request_id()) {
 642                                // DeepSeekR1 doesn't support thinking blocks
 643                                // And the AWS API demands that you strip them
 644                                return None;
 645                            }
 646                            let thinking = BedrockThinkingTextBlock::builder()
 647                                .text(text)
 648                                .set_signature(signature)
 649                                .build()
 650                                .context("failed to build reasoning block")
 651                                .log_err()?;
 652
 653                            Some(BedrockInnerContent::ReasoningContent(
 654                                BedrockThinkingBlock::ReasoningText(thinking),
 655                            ))
 656                        }
 657                        MessageContent::RedactedThinking(blob) => {
 658                            if model.contains(Model::DeepSeekR1.request_id()) {
 659                                // DeepSeekR1 doesn't support thinking blocks
 660                                // And the AWS API demands that you strip them
 661                                return None;
 662                            }
 663                            let redacted =
 664                                BedrockThinkingBlock::RedactedContent(BedrockBlob::new(blob));
 665
 666                            Some(BedrockInnerContent::ReasoningContent(redacted))
 667                        }
 668                        MessageContent::ToolUse(tool_use) => {
 669                            let input = if tool_use.input.is_null() {
 670                                // Bedrock API requires valid JsonValue, not null, for tool use input
 671                                value_to_aws_document(&serde_json::json!({}))
 672                            } else {
 673                                value_to_aws_document(&tool_use.input)
 674                            };
 675                            BedrockToolUseBlock::builder()
 676                                .name(tool_use.name.to_string())
 677                                .tool_use_id(tool_use.id.to_string())
 678                                .input(input)
 679                                .build()
 680                                .context("failed to build Bedrock tool use block")
 681                                .log_err()
 682                                .map(BedrockInnerContent::ToolUse)
 683                        },
 684                        MessageContent::ToolResult(tool_result) => {
 685                            BedrockToolResultBlock::builder()
 686                                .tool_use_id(tool_result.tool_use_id.to_string())
 687                                .content(match tool_result.content {
 688                                    LanguageModelToolResultContent::Text(text) => {
 689                                        BedrockToolResultContentBlock::Text(text.to_string())
 690                                    }
 691                                    LanguageModelToolResultContent::Image(_) => {
 692                                        BedrockToolResultContentBlock::Text(
 693                                            // TODO: Bedrock image support
 694                                            "[Tool responded with an image, but Zed doesn't support these in Bedrock models yet]".to_string()
 695                                        )
 696                                    }
 697                                })
 698                                .status({
 699                                    if tool_result.is_error {
 700                                        BedrockToolResultStatus::Error
 701                                    } else {
 702                                        BedrockToolResultStatus::Success
 703                                    }
 704                                })
 705                                .build()
 706                                .context("failed to build Bedrock tool result block")
 707                                .log_err()
 708                                .map(BedrockInnerContent::ToolResult)
 709                        }
 710                        _ => None,
 711                    })
 712                    .collect();
 713                if message.cache && supports_caching {
 714                    bedrock_message_content.push(BedrockInnerContent::CachePoint(
 715                        CachePointBlock::builder()
 716                            .r#type(CachePointType::Default)
 717                            .build()
 718                            .context("failed to build cache point block")?,
 719                    ));
 720                }
 721                let bedrock_role = match message.role {
 722                    Role::User => bedrock::BedrockRole::User,
 723                    Role::Assistant => bedrock::BedrockRole::Assistant,
 724                    Role::System => unreachable!("System role should never occur here"),
 725                };
 726                if let Some(last_message) = new_messages.last_mut() {
 727                    if last_message.role == bedrock_role {
 728                        last_message.content.extend(bedrock_message_content);
 729                        continue;
 730                    }
 731                }
 732                new_messages.push(
 733                    BedrockMessage::builder()
 734                        .role(bedrock_role)
 735                        .set_content(Some(bedrock_message_content))
 736                        .build()
 737                        .context("failed to build Bedrock message")?,
 738                );
 739            }
 740            Role::System => {
 741                if !system_message.is_empty() {
 742                    system_message.push_str("\n\n");
 743                }
 744                system_message.push_str(&message.string_contents());
 745            }
 746        }
 747    }
 748
 749    let mut tool_spec: Vec<BedrockTool> = request
 750        .tools
 751        .iter()
 752        .filter_map(|tool| {
 753            Some(BedrockTool::ToolSpec(
 754                BedrockToolSpec::builder()
 755                    .name(tool.name.clone())
 756                    .description(tool.description.clone())
 757                    .input_schema(BedrockToolInputSchema::Json(value_to_aws_document(
 758                        &tool.input_schema,
 759                    )))
 760                    .build()
 761                    .log_err()?,
 762            ))
 763        })
 764        .collect();
 765
 766    if !tool_spec.is_empty() && supports_caching {
 767        tool_spec.push(BedrockTool::CachePoint(
 768            CachePointBlock::builder()
 769                .r#type(CachePointType::Default)
 770                .build()
 771                .context("failed to build cache point block")?,
 772        ));
 773    }
 774
 775    let tool_choice = match request.tool_choice {
 776        Some(LanguageModelToolChoice::Auto) | None => {
 777            BedrockToolChoice::Auto(BedrockAutoToolChoice::builder().build())
 778        }
 779        Some(LanguageModelToolChoice::Any) => {
 780            BedrockToolChoice::Any(BedrockAnyToolChoice::builder().build())
 781        }
 782        Some(LanguageModelToolChoice::None) => {
 783            // For None, we still use Auto but will filter out tool calls in the response
 784            BedrockToolChoice::Auto(BedrockAutoToolChoice::builder().build())
 785        }
 786    };
 787    let tool_config: BedrockToolConfig = BedrockToolConfig::builder()
 788        .set_tools(Some(tool_spec))
 789        .tool_choice(tool_choice)
 790        .build()?;
 791
 792    Ok(bedrock::Request {
 793        model,
 794        messages: new_messages,
 795        max_tokens: max_output_tokens,
 796        system: Some(system_message),
 797        tools: Some(tool_config),
 798        thinking: if request.thinking_allowed
 799            && let BedrockModelMode::Thinking { budget_tokens } = mode
 800        {
 801            Some(bedrock::Thinking::Enabled { budget_tokens })
 802        } else {
 803            None
 804        },
 805        metadata: None,
 806        stop_sequences: Vec::new(),
 807        temperature: request.temperature.or(Some(default_temperature)),
 808        top_k: None,
 809        top_p: None,
 810    })
 811}
 812
 813// TODO: just call the ConverseOutput.usage() method:
 814// https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/operation/converse/struct.ConverseOutput.html#method.output
 815pub fn get_bedrock_tokens(
 816    request: LanguageModelRequest,
 817    cx: &App,
 818) -> BoxFuture<'static, Result<u64>> {
 819    cx.background_executor()
 820        .spawn(async move {
 821            let messages = request.messages;
 822            let mut tokens_from_images = 0;
 823            let mut string_messages = Vec::with_capacity(messages.len());
 824
 825            for message in messages {
 826                use language_model::MessageContent;
 827
 828                let mut string_contents = String::new();
 829
 830                for content in message.content {
 831                    match content {
 832                        MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
 833                            string_contents.push_str(&text);
 834                        }
 835                        MessageContent::RedactedThinking(_) => {}
 836                        MessageContent::Image(image) => {
 837                            tokens_from_images += image.estimate_tokens();
 838                        }
 839                        MessageContent::ToolUse(_tool_use) => {
 840                            // TODO: Estimate token usage from tool uses.
 841                        }
 842                        MessageContent::ToolResult(tool_result) => match tool_result.content {
 843                            LanguageModelToolResultContent::Text(text) => {
 844                                string_contents.push_str(&text);
 845                            }
 846                            LanguageModelToolResultContent::Image(image) => {
 847                                tokens_from_images += image.estimate_tokens();
 848                            }
 849                        },
 850                    }
 851                }
 852
 853                if !string_contents.is_empty() {
 854                    string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
 855                        role: match message.role {
 856                            Role::User => "user".into(),
 857                            Role::Assistant => "assistant".into(),
 858                            Role::System => "system".into(),
 859                        },
 860                        content: Some(string_contents),
 861                        name: None,
 862                        function_call: None,
 863                    });
 864                }
 865            }
 866
 867            // Tiktoken doesn't yet support these models, so we manually use the
 868            // same tokenizer as GPT-4.
 869            tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
 870                .map(|tokens| (tokens + tokens_from_images) as u64)
 871        })
 872        .boxed()
 873}
 874
 875pub fn map_to_language_model_completion_events(
 876    events: Pin<Box<dyn Send + Stream<Item = Result<BedrockStreamingResponse, BedrockError>>>>,
 877) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 878    struct RawToolUse {
 879        id: String,
 880        name: String,
 881        input_json: String,
 882    }
 883
 884    struct State {
 885        events: Pin<Box<dyn Send + Stream<Item = Result<BedrockStreamingResponse, BedrockError>>>>,
 886        tool_uses_by_index: HashMap<i32, RawToolUse>,
 887    }
 888
 889    let initial_state = State {
 890        events,
 891        tool_uses_by_index: HashMap::default(),
 892    };
 893
 894    futures::stream::unfold(initial_state, |mut state| async move {
 895        match state.events.next().await {
 896            Some(event_result) => match event_result {
 897                Ok(event) => {
 898                    let result = match event {
 899                        ConverseStreamOutput::ContentBlockDelta(cb_delta) => match cb_delta.delta {
 900                            Some(ContentBlockDelta::Text(text)) => {
 901                                Some(Ok(LanguageModelCompletionEvent::Text(text)))
 902                            }
 903                            Some(ContentBlockDelta::ToolUse(tool_output)) => {
 904                                if let Some(tool_use) = state
 905                                    .tool_uses_by_index
 906                                    .get_mut(&cb_delta.content_block_index)
 907                                {
 908                                    tool_use.input_json.push_str(tool_output.input());
 909                                }
 910                                None
 911                            }
 912                            Some(ContentBlockDelta::ReasoningContent(thinking)) => match thinking {
 913                                ReasoningContentBlockDelta::Text(thoughts) => {
 914                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 915                                        text: thoughts.clone(),
 916                                        signature: None,
 917                                    }))
 918                                }
 919                                ReasoningContentBlockDelta::Signature(sig) => {
 920                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 921                                        text: "".into(),
 922                                        signature: Some(sig),
 923                                    }))
 924                                }
 925                                ReasoningContentBlockDelta::RedactedContent(redacted) => {
 926                                    let content = String::from_utf8(redacted.into_inner())
 927                                        .unwrap_or("REDACTED".to_string());
 928                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 929                                        text: content,
 930                                        signature: None,
 931                                    }))
 932                                }
 933                                _ => None,
 934                            },
 935                            _ => None,
 936                        },
 937                        ConverseStreamOutput::ContentBlockStart(cb_start) => {
 938                            if let Some(ContentBlockStart::ToolUse(tool_start)) = cb_start.start {
 939                                state.tool_uses_by_index.insert(
 940                                    cb_start.content_block_index,
 941                                    RawToolUse {
 942                                        id: tool_start.tool_use_id,
 943                                        name: tool_start.name,
 944                                        input_json: String::new(),
 945                                    },
 946                                );
 947                            }
 948                            None
 949                        }
 950                        ConverseStreamOutput::ContentBlockStop(cb_stop) => state
 951                            .tool_uses_by_index
 952                            .remove(&cb_stop.content_block_index)
 953                            .map(|tool_use| {
 954                                let input = if tool_use.input_json.is_empty() {
 955                                    Value::Null
 956                                } else {
 957                                    serde_json::Value::from_str(&tool_use.input_json)
 958                                        .unwrap_or(Value::Null)
 959                                };
 960
 961                                Ok(LanguageModelCompletionEvent::ToolUse(
 962                                    LanguageModelToolUse {
 963                                        id: tool_use.id.into(),
 964                                        name: tool_use.name.into(),
 965                                        is_input_complete: true,
 966                                        raw_input: tool_use.input_json.clone(),
 967                                        input,
 968                                    },
 969                                ))
 970                            }),
 971                        ConverseStreamOutput::Metadata(cb_meta) => cb_meta.usage.map(|metadata| {
 972                            Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
 973                                input_tokens: metadata.input_tokens as u64,
 974                                output_tokens: metadata.output_tokens as u64,
 975                                cache_creation_input_tokens: metadata
 976                                    .cache_write_input_tokens
 977                                    .unwrap_or_default()
 978                                    as u64,
 979                                cache_read_input_tokens: metadata
 980                                    .cache_read_input_tokens
 981                                    .unwrap_or_default()
 982                                    as u64,
 983                            }))
 984                        }),
 985                        ConverseStreamOutput::MessageStop(message_stop) => {
 986                            let stop_reason = match message_stop.stop_reason {
 987                                StopReason::ToolUse => language_model::StopReason::ToolUse,
 988                                _ => language_model::StopReason::EndTurn,
 989                            };
 990                            Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason)))
 991                        }
 992                        _ => None,
 993                    };
 994
 995                    Some((result, state))
 996                }
 997                Err(err) => Some((
 998                    Some(Err(LanguageModelCompletionError::Other(anyhow!(err)))),
 999                    state,
1000                )),
1001            },
1002            None => None,
1003        }
1004    })
1005    .filter_map(|result| async move { result })
1006}
1007
1008struct ConfigurationView {
1009    access_key_id_editor: Entity<Editor>,
1010    secret_access_key_editor: Entity<Editor>,
1011    session_token_editor: Entity<Editor>,
1012    region_editor: Entity<Editor>,
1013    state: gpui::Entity<State>,
1014    load_credentials_task: Option<Task<()>>,
1015}
1016
1017impl ConfigurationView {
1018    const PLACEHOLDER_ACCESS_KEY_ID_TEXT: &'static str = "XXXXXXXXXXXXXXXX";
1019    const PLACEHOLDER_SECRET_ACCESS_KEY_TEXT: &'static str =
1020        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1021    const PLACEHOLDER_SESSION_TOKEN_TEXT: &'static str = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1022    const PLACEHOLDER_REGION: &'static str = "us-east-1";
1023
1024    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1025        cx.observe(&state, |_, _, cx| {
1026            cx.notify();
1027        })
1028        .detach();
1029
1030        let load_credentials_task = Some(cx.spawn({
1031            let state = state.clone();
1032            async move |this, cx| {
1033                if let Some(task) = state
1034                    .update(cx, |state, cx| state.authenticate(cx))
1035                    .log_err()
1036                {
1037                    // We don't log an error, because "not signed in" is also an error.
1038                    let _ = task.await;
1039                }
1040                this.update(cx, |this, cx| {
1041                    this.load_credentials_task = None;
1042                    cx.notify();
1043                })
1044                .log_err();
1045            }
1046        }));
1047
1048        Self {
1049            access_key_id_editor: cx.new(|cx| {
1050                let mut editor = Editor::single_line(window, cx);
1051                editor.set_placeholder_text(Self::PLACEHOLDER_ACCESS_KEY_ID_TEXT, cx);
1052                editor
1053            }),
1054            secret_access_key_editor: cx.new(|cx| {
1055                let mut editor = Editor::single_line(window, cx);
1056                editor.set_placeholder_text(Self::PLACEHOLDER_SECRET_ACCESS_KEY_TEXT, cx);
1057                editor
1058            }),
1059            session_token_editor: cx.new(|cx| {
1060                let mut editor = Editor::single_line(window, cx);
1061                editor.set_placeholder_text(Self::PLACEHOLDER_SESSION_TOKEN_TEXT, cx);
1062                editor
1063            }),
1064            region_editor: cx.new(|cx| {
1065                let mut editor = Editor::single_line(window, cx);
1066                editor.set_placeholder_text(Self::PLACEHOLDER_REGION, cx);
1067                editor
1068            }),
1069            state,
1070            load_credentials_task,
1071        }
1072    }
1073
1074    fn save_credentials(
1075        &mut self,
1076        _: &menu::Confirm,
1077        _window: &mut Window,
1078        cx: &mut Context<Self>,
1079    ) {
1080        let access_key_id = self
1081            .access_key_id_editor
1082            .read(cx)
1083            .text(cx)
1084            .to_string()
1085            .trim()
1086            .to_string();
1087        let secret_access_key = self
1088            .secret_access_key_editor
1089            .read(cx)
1090            .text(cx)
1091            .to_string()
1092            .trim()
1093            .to_string();
1094        let session_token = self
1095            .session_token_editor
1096            .read(cx)
1097            .text(cx)
1098            .to_string()
1099            .trim()
1100            .to_string();
1101        let session_token = if session_token.is_empty() {
1102            None
1103        } else {
1104            Some(session_token)
1105        };
1106        let region = self
1107            .region_editor
1108            .read(cx)
1109            .text(cx)
1110            .to_string()
1111            .trim()
1112            .to_string();
1113        let region = if region.is_empty() {
1114            "us-east-1".to_string()
1115        } else {
1116            region
1117        };
1118
1119        let state = self.state.clone();
1120        cx.spawn(async move |_, cx| {
1121            state
1122                .update(cx, |state, cx| {
1123                    let credentials: BedrockCredentials = BedrockCredentials {
1124                        region: region.clone(),
1125                        access_key_id: access_key_id.clone(),
1126                        secret_access_key: secret_access_key.clone(),
1127                        session_token: session_token.clone(),
1128                    };
1129
1130                    state.set_credentials(credentials, cx)
1131                })?
1132                .await
1133        })
1134        .detach_and_log_err(cx);
1135    }
1136
1137    fn reset_credentials(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1138        self.access_key_id_editor
1139            .update(cx, |editor, cx| editor.set_text("", window, cx));
1140        self.secret_access_key_editor
1141            .update(cx, |editor, cx| editor.set_text("", window, cx));
1142        self.session_token_editor
1143            .update(cx, |editor, cx| editor.set_text("", window, cx));
1144        self.region_editor
1145            .update(cx, |editor, cx| editor.set_text("", window, cx));
1146
1147        let state = self.state.clone();
1148        cx.spawn(async move |_, cx| {
1149            state
1150                .update(cx, |state, cx| state.reset_credentials(cx))?
1151                .await
1152        })
1153        .detach_and_log_err(cx);
1154    }
1155
1156    fn make_text_style(&self, cx: &Context<Self>) -> TextStyle {
1157        let settings = ThemeSettings::get_global(cx);
1158        TextStyle {
1159            color: cx.theme().colors().text,
1160            font_family: settings.ui_font.family.clone(),
1161            font_features: settings.ui_font.features.clone(),
1162            font_fallbacks: settings.ui_font.fallbacks.clone(),
1163            font_size: rems(0.875).into(),
1164            font_weight: settings.ui_font.weight,
1165            font_style: FontStyle::Normal,
1166            line_height: relative(1.3),
1167            background_color: None,
1168            underline: None,
1169            strikethrough: None,
1170            white_space: WhiteSpace::Normal,
1171            text_overflow: None,
1172            text_align: Default::default(),
1173            line_clamp: None,
1174        }
1175    }
1176
1177    fn make_input_styles(&self, cx: &Context<Self>) -> Div {
1178        let bg_color = cx.theme().colors().editor_background;
1179        let border_color = cx.theme().colors().border;
1180
1181        h_flex()
1182            .w_full()
1183            .px_2()
1184            .py_1()
1185            .bg(bg_color)
1186            .border_1()
1187            .border_color(border_color)
1188            .rounded_sm()
1189    }
1190
1191    fn should_render_editor(&self, cx: &Context<Self>) -> bool {
1192        self.state.read(cx).is_authenticated()
1193    }
1194}
1195
1196impl Render for ConfigurationView {
1197    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1198        let env_var_set = self.state.read(cx).credentials_from_env;
1199        let bedrock_settings = self.state.read(cx).settings.as_ref();
1200        let bedrock_method = bedrock_settings
1201            .as_ref()
1202            .and_then(|s| s.authentication_method.clone());
1203
1204        if self.load_credentials_task.is_some() {
1205            return div().child(Label::new("Loading credentials...")).into_any();
1206        }
1207
1208        if self.should_render_editor(cx) {
1209            return h_flex()
1210                .mt_1()
1211                .p_1()
1212                .justify_between()
1213                .rounded_md()
1214                .border_1()
1215                .border_color(cx.theme().colors().border)
1216                .bg(cx.theme().colors().background)
1217                .child(
1218                    h_flex()
1219                        .gap_1()
1220                        .child(Icon::new(IconName::Check).color(Color::Success))
1221                        .child(Label::new(if env_var_set {
1222                            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.")
1223                        } else {
1224                            match bedrock_method {
1225                                Some(BedrockAuthMethod::Automatic) => "You are using automatic credentials".into(),
1226                                Some(BedrockAuthMethod::NamedProfile) => {
1227                                    "You are using named profile".into()
1228                                },
1229                                Some(BedrockAuthMethod::SingleSignOn) => "You are using a single sign on profile".into(),
1230                                None => "You are using static credentials".into(),
1231                            }
1232                        })),
1233                )
1234                .child(
1235                    Button::new("reset-key", "Reset Key")
1236                        .icon(Some(IconName::Trash))
1237                        .icon_size(IconSize::Small)
1238                        .icon_position(IconPosition::Start)
1239                        .disabled(env_var_set || bedrock_method.is_some())
1240                        .when(env_var_set, |this| {
1241                            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.")))
1242                        })
1243                        .when(bedrock_method.is_some(), |this| {
1244                            this.tooltip(Tooltip::text("You cannot reset credentials as they're being derived, check Zed settings to understand how"))
1245                        })
1246                        .on_click(cx.listener(|this, _, window, cx| this.reset_credentials(window, cx))),
1247                )
1248                .into_any();
1249        }
1250
1251        v_flex()
1252            .size_full()
1253            .on_action(cx.listener(ConfigurationView::save_credentials))
1254            .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."))
1255            .child(Label::new("But, to access models on AWS, you need to:").mt_1())
1256            .child(
1257                List::new()
1258                    .child(
1259                        InstructionListItem::new(
1260                            "Grant permissions to the strategy you'll use according to the:",
1261                            Some("Prerequisites"),
1262                            Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
1263                        )
1264                    )
1265                    .child(
1266                        InstructionListItem::new(
1267                            "Select the models you would like access to:",
1268                            Some("Bedrock Model Catalog"),
1269                            Some("https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess"),
1270                        )
1271                    )
1272            )
1273            .child(self.render_static_credentials_ui(cx))
1274            .child(self.render_common_fields(cx))
1275            .child(
1276                Label::new(
1277                    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."),
1278                )
1279                    .size(LabelSize::Small)
1280                    .color(Color::Muted)
1281                    .my_1(),
1282            )
1283            .child(
1284                Label::new(
1285                    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}."),
1286                )
1287                    .size(LabelSize::Small)
1288                    .color(Color::Muted),
1289            )
1290            .into_any()
1291    }
1292}
1293
1294impl ConfigurationView {
1295    fn render_access_key_id_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1296        let text_style = self.make_text_style(cx);
1297
1298        EditorElement::new(
1299            &self.access_key_id_editor,
1300            EditorStyle {
1301                background: cx.theme().colors().editor_background,
1302                local_player: cx.theme().players().local(),
1303                text: text_style,
1304                ..Default::default()
1305            },
1306        )
1307    }
1308
1309    fn render_secret_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1310        let text_style = self.make_text_style(cx);
1311
1312        EditorElement::new(
1313            &self.secret_access_key_editor,
1314            EditorStyle {
1315                background: cx.theme().colors().editor_background,
1316                local_player: cx.theme().players().local(),
1317                text: text_style,
1318                ..Default::default()
1319            },
1320        )
1321    }
1322
1323    fn render_session_token_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1324        let text_style = self.make_text_style(cx);
1325
1326        EditorElement::new(
1327            &self.session_token_editor,
1328            EditorStyle {
1329                background: cx.theme().colors().editor_background,
1330                local_player: cx.theme().players().local(),
1331                text: text_style,
1332                ..Default::default()
1333            },
1334        )
1335    }
1336
1337    fn render_region_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1338        let text_style = self.make_text_style(cx);
1339
1340        EditorElement::new(
1341            &self.region_editor,
1342            EditorStyle {
1343                background: cx.theme().colors().editor_background,
1344                local_player: cx.theme().players().local(),
1345                text: text_style,
1346                ..Default::default()
1347            },
1348        )
1349    }
1350
1351    fn render_static_credentials_ui(&self, cx: &mut Context<Self>) -> AnyElement {
1352        v_flex()
1353            .my_2()
1354            .gap_1p5()
1355            .child(
1356                Label::new("Static Keys")
1357                    .size(LabelSize::Default)
1358                    .weight(FontWeight::BOLD),
1359            )
1360            .child(
1361                Label::new(
1362                    "This method uses your AWS access key ID and secret access key directly.",
1363                )
1364            )
1365            .child(
1366                List::new()
1367                    .child(InstructionListItem::new(
1368                        "Create an IAM user in the AWS console with programmatic access",
1369                        Some("IAM Console"),
1370                        Some("https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/users"),
1371                    ))
1372                    .child(InstructionListItem::new(
1373                        "Attach the necessary Bedrock permissions to this ",
1374                        Some("user"),
1375                        Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
1376                    ))
1377                    .child(InstructionListItem::text_only(
1378                        "Copy the access key ID and secret access key when provided",
1379                    ))
1380                    .child(InstructionListItem::text_only(
1381                        "Enter these credentials below",
1382                    )),
1383            )
1384            .child(
1385                v_flex()
1386                    .gap_0p5()
1387                    .child(Label::new("Access Key ID").size(LabelSize::Small))
1388                    .child(
1389                        self.make_input_styles(cx)
1390                            .child(self.render_access_key_id_editor(cx)),
1391                    ),
1392            )
1393            .child(
1394                v_flex()
1395                    .gap_0p5()
1396                    .child(Label::new("Secret Access Key").size(LabelSize::Small))
1397                    .child(self.make_input_styles(cx).child(self.render_secret_key_editor(cx))),
1398            )
1399            .child(
1400                v_flex()
1401                    .gap_0p5()
1402                    .child(Label::new("Session Token (Optional)").size(LabelSize::Small))
1403                    .child(
1404                        self.make_input_styles(cx)
1405                            .child(self.render_session_token_editor(cx)),
1406                    ),
1407            )
1408            .into_any_element()
1409    }
1410
1411    fn render_common_fields(&self, cx: &mut Context<Self>) -> AnyElement {
1412        v_flex()
1413            .gap_0p5()
1414            .child(Label::new("Region").size(LabelSize::Small))
1415            .child(
1416                self.make_input_styles(cx)
1417                    .child(self.render_region_editor(cx)),
1418            )
1419            .into_any_element()
1420    }
1421}