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