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    handler: 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        let tokio_handle = Tokio::handle(cx);
 262
 263        let coerced_client = AwsHttpClient::new(http_client.clone(), tokio_handle.clone());
 264
 265        Self {
 266            http_client: coerced_client,
 267            handler: tokio_handle.clone(),
 268            state,
 269        }
 270    }
 271
 272    fn create_language_model(&self, model: bedrock::Model) -> Arc<dyn LanguageModel> {
 273        Arc::new(BedrockModel {
 274            id: LanguageModelId::from(model.id().to_string()),
 275            model,
 276            http_client: self.http_client.clone(),
 277            handler: self.handler.clone(),
 278            state: self.state.clone(),
 279            client: OnceCell::new(),
 280            request_limiter: RateLimiter::new(4),
 281        })
 282    }
 283}
 284
 285impl LanguageModelProvider for BedrockLanguageModelProvider {
 286    fn id(&self) -> LanguageModelProviderId {
 287        PROVIDER_ID
 288    }
 289
 290    fn name(&self) -> LanguageModelProviderName {
 291        PROVIDER_NAME
 292    }
 293
 294    fn icon(&self) -> IconName {
 295        IconName::AiBedrock
 296    }
 297
 298    fn default_model(&self, _cx: &App) -> Option<Arc<dyn LanguageModel>> {
 299        Some(self.create_language_model(bedrock::Model::default()))
 300    }
 301
 302    fn default_fast_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
 303        let region = self.state.read(cx).get_region();
 304        Some(self.create_language_model(bedrock::Model::default_fast(region.as_str())))
 305    }
 306
 307    fn provided_models(&self, cx: &App) -> Vec<Arc<dyn LanguageModel>> {
 308        let mut models = BTreeMap::default();
 309
 310        for model in bedrock::Model::iter() {
 311            if !matches!(model, bedrock::Model::Custom { .. }) {
 312                // TODO: Sonnet 3.7 vs. 3.7 Thinking bug is here.
 313                models.insert(model.id().to_string(), model);
 314            }
 315        }
 316
 317        // Override with available models from settings
 318        for model in AllLanguageModelSettings::get_global(cx)
 319            .bedrock
 320            .available_models
 321            .iter()
 322        {
 323            models.insert(
 324                model.name.clone(),
 325                bedrock::Model::Custom {
 326                    name: model.name.clone(),
 327                    display_name: model.display_name.clone(),
 328                    max_tokens: model.max_tokens,
 329                    max_output_tokens: model.max_output_tokens,
 330                    default_temperature: model.default_temperature,
 331                    cache_configuration: model.cache_configuration.as_ref().map(|config| {
 332                        bedrock::BedrockModelCacheConfiguration {
 333                            max_cache_anchors: config.max_cache_anchors,
 334                            min_total_token: config.min_total_token,
 335                        }
 336                    }),
 337                },
 338            );
 339        }
 340
 341        models
 342            .into_values()
 343            .map(|model| self.create_language_model(model))
 344            .collect()
 345    }
 346
 347    fn is_authenticated(&self, cx: &App) -> bool {
 348        self.state.read(cx).is_authenticated()
 349    }
 350
 351    fn authenticate(&self, cx: &mut App) -> Task<Result<(), AuthenticateError>> {
 352        self.state.update(cx, |state, cx| state.authenticate(cx))
 353    }
 354
 355    fn configuration_view(&self, window: &mut Window, cx: &mut App) -> AnyView {
 356        cx.new(|cx| ConfigurationView::new(self.state.clone(), window, cx))
 357            .into()
 358    }
 359
 360    fn reset_credentials(&self, cx: &mut App) -> Task<Result<()>> {
 361        self.state
 362            .update(cx, |state, cx| state.reset_credentials(cx))
 363    }
 364}
 365
 366impl LanguageModelProviderState for BedrockLanguageModelProvider {
 367    type ObservableEntity = State;
 368
 369    fn observable_entity(&self) -> Option<gpui::Entity<Self::ObservableEntity>> {
 370        Some(self.state.clone())
 371    }
 372}
 373
 374struct BedrockModel {
 375    id: LanguageModelId,
 376    model: Model,
 377    http_client: AwsHttpClient,
 378    handler: tokio::runtime::Handle,
 379    client: OnceCell<BedrockClient>,
 380    state: gpui::Entity<State>,
 381    request_limiter: RateLimiter,
 382}
 383
 384impl BedrockModel {
 385    fn get_or_init_client(&self, cx: &AsyncApp) -> anyhow::Result<&BedrockClient> {
 386        self.client
 387            .get_or_try_init_blocking(|| {
 388                let (auth_method, credentials, endpoint, region, settings) =
 389                    cx.read_entity(&self.state, |state, _cx| {
 390                        let auth_method = state
 391                            .settings
 392                            .as_ref()
 393                            .and_then(|s| s.authentication_method.clone());
 394
 395                        let endpoint = state.settings.as_ref().and_then(|s| s.endpoint.clone());
 396
 397                        let region = state.get_region();
 398
 399                        (
 400                            auth_method,
 401                            state.credentials.clone(),
 402                            endpoint,
 403                            region,
 404                            state.settings.clone(),
 405                        )
 406                    })?;
 407
 408                let mut config_builder = aws_config::defaults(BehaviorVersion::latest())
 409                    .stalled_stream_protection(StalledStreamProtectionConfig::disabled())
 410                    .http_client(self.http_client.clone())
 411                    .region(Region::new(region))
 412                    .timeout_config(TimeoutConfig::disabled());
 413
 414                if let Some(endpoint_url) = endpoint {
 415                    if !endpoint_url.is_empty() {
 416                        config_builder = config_builder.endpoint_url(endpoint_url);
 417                    }
 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.handler.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                    if last_message.role == bedrock_role {
 732                        last_message.content.extend(bedrock_message_content);
 733                        continue;
 734                    }
 735                }
 736                new_messages.push(
 737                    BedrockMessage::builder()
 738                        .role(bedrock_role)
 739                        .set_content(Some(bedrock_message_content))
 740                        .build()
 741                        .context("failed to build Bedrock message")?,
 742                );
 743            }
 744            Role::System => {
 745                if !system_message.is_empty() {
 746                    system_message.push_str("\n\n");
 747                }
 748                system_message.push_str(&message.string_contents());
 749            }
 750        }
 751    }
 752
 753    let mut tool_spec: Vec<BedrockTool> = request
 754        .tools
 755        .iter()
 756        .filter_map(|tool| {
 757            Some(BedrockTool::ToolSpec(
 758                BedrockToolSpec::builder()
 759                    .name(tool.name.clone())
 760                    .description(tool.description.clone())
 761                    .input_schema(BedrockToolInputSchema::Json(value_to_aws_document(
 762                        &tool.input_schema,
 763                    )))
 764                    .build()
 765                    .log_err()?,
 766            ))
 767        })
 768        .collect();
 769
 770    if !tool_spec.is_empty() && supports_caching {
 771        tool_spec.push(BedrockTool::CachePoint(
 772            CachePointBlock::builder()
 773                .r#type(CachePointType::Default)
 774                .build()
 775                .context("failed to build cache point block")?,
 776        ));
 777    }
 778
 779    let tool_choice = match request.tool_choice {
 780        Some(LanguageModelToolChoice::Auto) | None => {
 781            BedrockToolChoice::Auto(BedrockAutoToolChoice::builder().build())
 782        }
 783        Some(LanguageModelToolChoice::Any) => {
 784            BedrockToolChoice::Any(BedrockAnyToolChoice::builder().build())
 785        }
 786        Some(LanguageModelToolChoice::None) => {
 787            // For None, we still use Auto but will filter out tool calls in the response
 788            BedrockToolChoice::Auto(BedrockAutoToolChoice::builder().build())
 789        }
 790    };
 791    let tool_config: BedrockToolConfig = BedrockToolConfig::builder()
 792        .set_tools(Some(tool_spec))
 793        .tool_choice(tool_choice)
 794        .build()?;
 795
 796    Ok(bedrock::Request {
 797        model,
 798        messages: new_messages,
 799        max_tokens: max_output_tokens,
 800        system: Some(system_message),
 801        tools: Some(tool_config),
 802        thinking: if let BedrockModelMode::Thinking { budget_tokens } = mode {
 803            Some(bedrock::Thinking::Enabled { budget_tokens })
 804        } else {
 805            None
 806        },
 807        metadata: None,
 808        stop_sequences: Vec::new(),
 809        temperature: request.temperature.or(Some(default_temperature)),
 810        top_k: None,
 811        top_p: None,
 812    })
 813}
 814
 815// TODO: just call the ConverseOutput.usage() method:
 816// https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/operation/converse/struct.ConverseOutput.html#method.output
 817pub fn get_bedrock_tokens(
 818    request: LanguageModelRequest,
 819    cx: &App,
 820) -> BoxFuture<'static, Result<u64>> {
 821    cx.background_executor()
 822        .spawn(async move {
 823            let messages = request.messages;
 824            let mut tokens_from_images = 0;
 825            let mut string_messages = Vec::with_capacity(messages.len());
 826
 827            for message in messages {
 828                use language_model::MessageContent;
 829
 830                let mut string_contents = String::new();
 831
 832                for content in message.content {
 833                    match content {
 834                        MessageContent::Text(text) | MessageContent::Thinking { text, .. } => {
 835                            string_contents.push_str(&text);
 836                        }
 837                        MessageContent::RedactedThinking(_) => {}
 838                        MessageContent::Image(image) => {
 839                            tokens_from_images += image.estimate_tokens();
 840                        }
 841                        MessageContent::ToolUse(_tool_use) => {
 842                            // TODO: Estimate token usage from tool uses.
 843                        }
 844                        MessageContent::ToolResult(tool_result) => match tool_result.content {
 845                            LanguageModelToolResultContent::Text(text) => {
 846                                string_contents.push_str(&text);
 847                            }
 848                            LanguageModelToolResultContent::Image(image) => {
 849                                tokens_from_images += image.estimate_tokens();
 850                            }
 851                        },
 852                    }
 853                }
 854
 855                if !string_contents.is_empty() {
 856                    string_messages.push(tiktoken_rs::ChatCompletionRequestMessage {
 857                        role: match message.role {
 858                            Role::User => "user".into(),
 859                            Role::Assistant => "assistant".into(),
 860                            Role::System => "system".into(),
 861                        },
 862                        content: Some(string_contents),
 863                        name: None,
 864                        function_call: None,
 865                    });
 866                }
 867            }
 868
 869            // Tiktoken doesn't yet support these models, so we manually use the
 870            // same tokenizer as GPT-4.
 871            tiktoken_rs::num_tokens_from_messages("gpt-4", &string_messages)
 872                .map(|tokens| (tokens + tokens_from_images) as u64)
 873        })
 874        .boxed()
 875}
 876
 877pub fn map_to_language_model_completion_events(
 878    events: Pin<Box<dyn Send + Stream<Item = Result<BedrockStreamingResponse, BedrockError>>>>,
 879) -> impl Stream<Item = Result<LanguageModelCompletionEvent, LanguageModelCompletionError>> {
 880    struct RawToolUse {
 881        id: String,
 882        name: String,
 883        input_json: String,
 884    }
 885
 886    struct State {
 887        events: Pin<Box<dyn Send + Stream<Item = Result<BedrockStreamingResponse, BedrockError>>>>,
 888        tool_uses_by_index: HashMap<i32, RawToolUse>,
 889    }
 890
 891    let initial_state = State {
 892        events,
 893        tool_uses_by_index: HashMap::default(),
 894    };
 895
 896    futures::stream::unfold(initial_state, |mut state| async move {
 897        match state.events.next().await {
 898            Some(event_result) => match event_result {
 899                Ok(event) => {
 900                    let result = match event {
 901                        ConverseStreamOutput::ContentBlockDelta(cb_delta) => match cb_delta.delta {
 902                            Some(ContentBlockDelta::Text(text)) => {
 903                                Some(Ok(LanguageModelCompletionEvent::Text(text)))
 904                            }
 905                            Some(ContentBlockDelta::ToolUse(tool_output)) => {
 906                                if let Some(tool_use) = state
 907                                    .tool_uses_by_index
 908                                    .get_mut(&cb_delta.content_block_index)
 909                                {
 910                                    tool_use.input_json.push_str(tool_output.input());
 911                                }
 912                                None
 913                            }
 914                            Some(ContentBlockDelta::ReasoningContent(thinking)) => match thinking {
 915                                ReasoningContentBlockDelta::Text(thoughts) => {
 916                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 917                                        text: thoughts.clone(),
 918                                        signature: None,
 919                                    }))
 920                                }
 921                                ReasoningContentBlockDelta::Signature(sig) => {
 922                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 923                                        text: "".into(),
 924                                        signature: Some(sig),
 925                                    }))
 926                                }
 927                                ReasoningContentBlockDelta::RedactedContent(redacted) => {
 928                                    let content = String::from_utf8(redacted.into_inner())
 929                                        .unwrap_or("REDACTED".to_string());
 930                                    Some(Ok(LanguageModelCompletionEvent::Thinking {
 931                                        text: content,
 932                                        signature: None,
 933                                    }))
 934                                }
 935                                _ => None,
 936                            },
 937                            _ => None,
 938                        },
 939                        ConverseStreamOutput::ContentBlockStart(cb_start) => {
 940                            if let Some(ContentBlockStart::ToolUse(tool_start)) = cb_start.start {
 941                                state.tool_uses_by_index.insert(
 942                                    cb_start.content_block_index,
 943                                    RawToolUse {
 944                                        id: tool_start.tool_use_id,
 945                                        name: tool_start.name,
 946                                        input_json: String::new(),
 947                                    },
 948                                );
 949                            }
 950                            None
 951                        }
 952                        ConverseStreamOutput::ContentBlockStop(cb_stop) => state
 953                            .tool_uses_by_index
 954                            .remove(&cb_stop.content_block_index)
 955                            .map(|tool_use| {
 956                                let input = if tool_use.input_json.is_empty() {
 957                                    Value::Null
 958                                } else {
 959                                    serde_json::Value::from_str(&tool_use.input_json)
 960                                        .unwrap_or(Value::Null)
 961                                };
 962
 963                                Ok(LanguageModelCompletionEvent::ToolUse(
 964                                    LanguageModelToolUse {
 965                                        id: tool_use.id.into(),
 966                                        name: tool_use.name.into(),
 967                                        is_input_complete: true,
 968                                        raw_input: tool_use.input_json.clone(),
 969                                        input,
 970                                    },
 971                                ))
 972                            }),
 973                        ConverseStreamOutput::Metadata(cb_meta) => cb_meta.usage.map(|metadata| {
 974                            Ok(LanguageModelCompletionEvent::UsageUpdate(TokenUsage {
 975                                input_tokens: metadata.input_tokens as u64,
 976                                output_tokens: metadata.output_tokens as u64,
 977                                cache_creation_input_tokens: metadata
 978                                    .cache_write_input_tokens
 979                                    .unwrap_or_default()
 980                                    as u64,
 981                                cache_read_input_tokens: metadata
 982                                    .cache_read_input_tokens
 983                                    .unwrap_or_default()
 984                                    as u64,
 985                            }))
 986                        }),
 987                        ConverseStreamOutput::MessageStop(message_stop) => {
 988                            let stop_reason = match message_stop.stop_reason {
 989                                StopReason::ToolUse => language_model::StopReason::ToolUse,
 990                                _ => language_model::StopReason::EndTurn,
 991                            };
 992                            Some(Ok(LanguageModelCompletionEvent::Stop(stop_reason)))
 993                        }
 994                        _ => None,
 995                    };
 996
 997                    Some((result, state))
 998                }
 999                Err(err) => Some((
1000                    Some(Err(LanguageModelCompletionError::Other(anyhow!(err)))),
1001                    state,
1002                )),
1003            },
1004            None => None,
1005        }
1006    })
1007    .filter_map(|result| async move { result })
1008}
1009
1010struct ConfigurationView {
1011    access_key_id_editor: Entity<Editor>,
1012    secret_access_key_editor: Entity<Editor>,
1013    session_token_editor: Entity<Editor>,
1014    region_editor: Entity<Editor>,
1015    state: gpui::Entity<State>,
1016    load_credentials_task: Option<Task<()>>,
1017}
1018
1019impl ConfigurationView {
1020    const PLACEHOLDER_ACCESS_KEY_ID_TEXT: &'static str = "XXXXXXXXXXXXXXXX";
1021    const PLACEHOLDER_SECRET_ACCESS_KEY_TEXT: &'static str =
1022        "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1023    const PLACEHOLDER_SESSION_TOKEN_TEXT: &'static str = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
1024    const PLACEHOLDER_REGION: &'static str = "us-east-1";
1025
1026    fn new(state: gpui::Entity<State>, window: &mut Window, cx: &mut Context<Self>) -> Self {
1027        cx.observe(&state, |_, _, cx| {
1028            cx.notify();
1029        })
1030        .detach();
1031
1032        let load_credentials_task = Some(cx.spawn({
1033            let state = state.clone();
1034            async move |this, cx| {
1035                if let Some(task) = state
1036                    .update(cx, |state, cx| state.authenticate(cx))
1037                    .log_err()
1038                {
1039                    // We don't log an error, because "not signed in" is also an error.
1040                    let _ = task.await;
1041                }
1042                this.update(cx, |this, cx| {
1043                    this.load_credentials_task = None;
1044                    cx.notify();
1045                })
1046                .log_err();
1047            }
1048        }));
1049
1050        Self {
1051            access_key_id_editor: cx.new(|cx| {
1052                let mut editor = Editor::single_line(window, cx);
1053                editor.set_placeholder_text(Self::PLACEHOLDER_ACCESS_KEY_ID_TEXT, cx);
1054                editor
1055            }),
1056            secret_access_key_editor: cx.new(|cx| {
1057                let mut editor = Editor::single_line(window, cx);
1058                editor.set_placeholder_text(Self::PLACEHOLDER_SECRET_ACCESS_KEY_TEXT, cx);
1059                editor
1060            }),
1061            session_token_editor: cx.new(|cx| {
1062                let mut editor = Editor::single_line(window, cx);
1063                editor.set_placeholder_text(Self::PLACEHOLDER_SESSION_TOKEN_TEXT, cx);
1064                editor
1065            }),
1066            region_editor: cx.new(|cx| {
1067                let mut editor = Editor::single_line(window, cx);
1068                editor.set_placeholder_text(Self::PLACEHOLDER_REGION, cx);
1069                editor
1070            }),
1071            state,
1072            load_credentials_task,
1073        }
1074    }
1075
1076    fn save_credentials(
1077        &mut self,
1078        _: &menu::Confirm,
1079        _window: &mut Window,
1080        cx: &mut Context<Self>,
1081    ) {
1082        let access_key_id = self
1083            .access_key_id_editor
1084            .read(cx)
1085            .text(cx)
1086            .to_string()
1087            .trim()
1088            .to_string();
1089        let secret_access_key = self
1090            .secret_access_key_editor
1091            .read(cx)
1092            .text(cx)
1093            .to_string()
1094            .trim()
1095            .to_string();
1096        let session_token = self
1097            .session_token_editor
1098            .read(cx)
1099            .text(cx)
1100            .to_string()
1101            .trim()
1102            .to_string();
1103        let session_token = if session_token.is_empty() {
1104            None
1105        } else {
1106            Some(session_token)
1107        };
1108        let region = self
1109            .region_editor
1110            .read(cx)
1111            .text(cx)
1112            .to_string()
1113            .trim()
1114            .to_string();
1115        let region = if region.is_empty() {
1116            "us-east-1".to_string()
1117        } else {
1118            region
1119        };
1120
1121        let state = self.state.clone();
1122        cx.spawn(async move |_, cx| {
1123            state
1124                .update(cx, |state, cx| {
1125                    let credentials: BedrockCredentials = BedrockCredentials {
1126                        region: region.clone(),
1127                        access_key_id: access_key_id.clone(),
1128                        secret_access_key: secret_access_key.clone(),
1129                        session_token: session_token.clone(),
1130                    };
1131
1132                    state.set_credentials(credentials, cx)
1133                })?
1134                .await
1135        })
1136        .detach_and_log_err(cx);
1137    }
1138
1139    fn reset_credentials(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1140        self.access_key_id_editor
1141            .update(cx, |editor, cx| editor.set_text("", window, cx));
1142        self.secret_access_key_editor
1143            .update(cx, |editor, cx| editor.set_text("", window, cx));
1144        self.session_token_editor
1145            .update(cx, |editor, cx| editor.set_text("", window, cx));
1146        self.region_editor
1147            .update(cx, |editor, cx| editor.set_text("", window, cx));
1148
1149        let state = self.state.clone();
1150        cx.spawn(async move |_, cx| {
1151            state
1152                .update(cx, |state, cx| state.reset_credentials(cx))?
1153                .await
1154        })
1155        .detach_and_log_err(cx);
1156    }
1157
1158    fn make_text_style(&self, cx: &Context<Self>) -> TextStyle {
1159        let settings = ThemeSettings::get_global(cx);
1160        TextStyle {
1161            color: cx.theme().colors().text,
1162            font_family: settings.ui_font.family.clone(),
1163            font_features: settings.ui_font.features.clone(),
1164            font_fallbacks: settings.ui_font.fallbacks.clone(),
1165            font_size: rems(0.875).into(),
1166            font_weight: settings.ui_font.weight,
1167            font_style: FontStyle::Normal,
1168            line_height: relative(1.3),
1169            background_color: None,
1170            underline: None,
1171            strikethrough: None,
1172            white_space: WhiteSpace::Normal,
1173            text_overflow: None,
1174            text_align: Default::default(),
1175            line_clamp: None,
1176        }
1177    }
1178
1179    fn make_input_styles(&self, cx: &Context<Self>) -> Div {
1180        let bg_color = cx.theme().colors().editor_background;
1181        let border_color = cx.theme().colors().border;
1182
1183        h_flex()
1184            .w_full()
1185            .px_2()
1186            .py_1()
1187            .bg(bg_color)
1188            .border_1()
1189            .border_color(border_color)
1190            .rounded_sm()
1191    }
1192
1193    fn should_render_editor(&self, cx: &Context<Self>) -> bool {
1194        self.state.read(cx).is_authenticated()
1195    }
1196}
1197
1198impl Render for ConfigurationView {
1199    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1200        let env_var_set = self.state.read(cx).credentials_from_env;
1201        let bedrock_settings = self.state.read(cx).settings.as_ref();
1202        let bedrock_method = bedrock_settings
1203            .as_ref()
1204            .and_then(|s| s.authentication_method.clone());
1205
1206        if self.load_credentials_task.is_some() {
1207            return div().child(Label::new("Loading credentials...")).into_any();
1208        }
1209
1210        if self.should_render_editor(cx) {
1211            return h_flex()
1212                .mt_1()
1213                .p_1()
1214                .justify_between()
1215                .rounded_md()
1216                .border_1()
1217                .border_color(cx.theme().colors().border)
1218                .bg(cx.theme().colors().background)
1219                .child(
1220                    h_flex()
1221                        .gap_1()
1222                        .child(Icon::new(IconName::Check).color(Color::Success))
1223                        .child(Label::new(if env_var_set {
1224                            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.")
1225                        } else {
1226                            match bedrock_method {
1227                                Some(BedrockAuthMethod::Automatic) => "You are using automatic credentials".into(),
1228                                Some(BedrockAuthMethod::NamedProfile) => {
1229                                    "You are using named profile".into()
1230                                },
1231                                Some(BedrockAuthMethod::SingleSignOn) => "You are using a single sign on profile".into(),
1232                                None => "You are using static credentials".into(),
1233                            }
1234                        })),
1235                )
1236                .child(
1237                    Button::new("reset-key", "Reset Key")
1238                        .icon(Some(IconName::Trash))
1239                        .icon_size(IconSize::Small)
1240                        .icon_position(IconPosition::Start)
1241                        .disabled(env_var_set || bedrock_method.is_some())
1242                        .when(env_var_set, |this| {
1243                            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.")))
1244                        })
1245                        .when(bedrock_method.is_some(), |this| {
1246                            this.tooltip(Tooltip::text("You cannot reset credentials as they're being derived, check Zed settings to understand how"))
1247                        })
1248                        .on_click(cx.listener(|this, _, window, cx| this.reset_credentials(window, cx))),
1249                )
1250                .into_any();
1251        }
1252
1253        v_flex()
1254            .size_full()
1255            .on_action(cx.listener(ConfigurationView::save_credentials))
1256            .child(Label::new("To use Zed's assistant with Bedrock, you can set a custom authentication strategy through the settings.json, or use static credentials."))
1257            .child(Label::new("But, to access models on AWS, you need to:").mt_1())
1258            .child(
1259                List::new()
1260                    .child(
1261                        InstructionListItem::new(
1262                            "Grant permissions to the strategy you'll use according to the:",
1263                            Some("Prerequisites"),
1264                            Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
1265                        )
1266                    )
1267                    .child(
1268                        InstructionListItem::new(
1269                            "Select the models you would like access to:",
1270                            Some("Bedrock Model Catalog"),
1271                            Some("https://us-east-1.console.aws.amazon.com/bedrock/home?region=us-east-1#/modelaccess"),
1272                        )
1273                    )
1274            )
1275            .child(self.render_static_credentials_ui(cx))
1276            .child(self.render_common_fields(cx))
1277            .child(
1278                Label::new(
1279                    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."),
1280                )
1281                    .size(LabelSize::Small)
1282                    .color(Color::Muted)
1283                    .my_1(),
1284            )
1285            .child(
1286                Label::new(
1287                    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}."),
1288                )
1289                    .size(LabelSize::Small)
1290                    .color(Color::Muted),
1291            )
1292            .into_any()
1293    }
1294}
1295
1296impl ConfigurationView {
1297    fn render_access_key_id_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1298        let text_style = self.make_text_style(cx);
1299
1300        EditorElement::new(
1301            &self.access_key_id_editor,
1302            EditorStyle {
1303                background: cx.theme().colors().editor_background,
1304                local_player: cx.theme().players().local(),
1305                text: text_style,
1306                ..Default::default()
1307            },
1308        )
1309    }
1310
1311    fn render_secret_key_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1312        let text_style = self.make_text_style(cx);
1313
1314        EditorElement::new(
1315            &self.secret_access_key_editor,
1316            EditorStyle {
1317                background: cx.theme().colors().editor_background,
1318                local_player: cx.theme().players().local(),
1319                text: text_style,
1320                ..Default::default()
1321            },
1322        )
1323    }
1324
1325    fn render_session_token_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1326        let text_style = self.make_text_style(cx);
1327
1328        EditorElement::new(
1329            &self.session_token_editor,
1330            EditorStyle {
1331                background: cx.theme().colors().editor_background,
1332                local_player: cx.theme().players().local(),
1333                text: text_style,
1334                ..Default::default()
1335            },
1336        )
1337    }
1338
1339    fn render_region_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
1340        let text_style = self.make_text_style(cx);
1341
1342        EditorElement::new(
1343            &self.region_editor,
1344            EditorStyle {
1345                background: cx.theme().colors().editor_background,
1346                local_player: cx.theme().players().local(),
1347                text: text_style,
1348                ..Default::default()
1349            },
1350        )
1351    }
1352
1353    fn render_static_credentials_ui(&self, cx: &mut Context<Self>) -> AnyElement {
1354        v_flex()
1355            .my_2()
1356            .gap_1p5()
1357            .child(
1358                Label::new("Static Keys")
1359                    .size(LabelSize::Default)
1360                    .weight(FontWeight::BOLD),
1361            )
1362            .child(
1363                Label::new(
1364                    "This method uses your AWS access key ID and secret access key directly.",
1365                )
1366            )
1367            .child(
1368                List::new()
1369                    .child(InstructionListItem::new(
1370                        "Create an IAM user in the AWS console with programmatic access",
1371                        Some("IAM Console"),
1372                        Some("https://us-east-1.console.aws.amazon.com/iam/home?region=us-east-1#/users"),
1373                    ))
1374                    .child(InstructionListItem::new(
1375                        "Attach the necessary Bedrock permissions to this ",
1376                        Some("user"),
1377                        Some("https://docs.aws.amazon.com/bedrock/latest/userguide/inference-prereq.html"),
1378                    ))
1379                    .child(InstructionListItem::text_only(
1380                        "Copy the access key ID and secret access key when provided",
1381                    ))
1382                    .child(InstructionListItem::text_only(
1383                        "Enter these credentials below",
1384                    )),
1385            )
1386            .child(
1387                v_flex()
1388                    .gap_0p5()
1389                    .child(Label::new("Access Key ID").size(LabelSize::Small))
1390                    .child(
1391                        self.make_input_styles(cx)
1392                            .child(self.render_access_key_id_editor(cx)),
1393                    ),
1394            )
1395            .child(
1396                v_flex()
1397                    .gap_0p5()
1398                    .child(Label::new("Secret Access Key").size(LabelSize::Small))
1399                    .child(self.make_input_styles(cx).child(self.render_secret_key_editor(cx))),
1400            )
1401            .child(
1402                v_flex()
1403                    .gap_0p5()
1404                    .child(Label::new("Session Token (Optional)").size(LabelSize::Small))
1405                    .child(
1406                        self.make_input_styles(cx)
1407                            .child(self.render_session_token_editor(cx)),
1408                    ),
1409            )
1410            .into_any_element()
1411    }
1412
1413    fn render_common_fields(&self, cx: &mut Context<Self>) -> AnyElement {
1414        v_flex()
1415            .gap_0p5()
1416            .child(Label::new("Region").size(LabelSize::Small))
1417            .child(
1418                self.make_input_styles(cx)
1419                    .child(self.render_region_editor(cx)),
1420            )
1421            .into_any_element()
1422    }
1423}