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