-
Notifications
You must be signed in to change notification settings - Fork 284
Expand file tree
/
Copy pathinit.go
More file actions
2034 lines (1754 loc) · 68 KB
/
init.go
File metadata and controls
2034 lines (1754 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"azureaiagent/internal/exterrors"
"azureaiagent/internal/pkg/agents/agent_yaml"
"azureaiagent/internal/pkg/agents/registry_api"
"azureaiagent/internal/pkg/azure"
"azureaiagent/internal/project"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices/v2"
"github.com/azure/azure-dev/cli/azd/pkg/azdext"
"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/tools/github"
"github.com/fatih/color"
"github.com/spf13/cobra"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/structpb"
"gopkg.in/yaml.v3"
)
type initFlags struct {
*rootFlagsDefinition
projectResourceId string
modelDeployment string
model string
manifestPointer string
src string
host string
env string
}
// AiProjectResourceConfig represents the configuration for an AI project resource
type AiProjectResourceConfig struct {
Models []map[string]interface{} `json:"models,omitempty"`
}
type InitAction struct {
azdClient *azdext.AzdClient
//azureClient *azure.AzureClient
azureContext *azdext.AzureContext
//composedResources []*azdext.ComposedResource
console input.Console
credential azcore.TokenCredential
modelCatalog map[string]*azdext.AiModel
locationWarningShown bool
projectConfig *azdext.ProjectConfig
environment *azdext.Environment
flags *initFlags
deploymentDetails []project.Deployment
httpClient *http.Client
}
// GitHubUrlInfo holds parsed information from a GitHub URL
type GitHubUrlInfo struct {
RepoSlug string
Branch string
FilePath string
Hostname string
}
const AiAgentHost = "azure.ai.agent"
const ContainerAppHost = "containerapp"
// checkAiModelServiceAvailable is a temporary check to ensure the azd host supports
// required gRPC services. Remove once azd core enforces requiredAzdVersion.
func checkAiModelServiceAvailable(ctx context.Context, azdClient *azdext.AzdClient) error {
_, err := azdClient.Ai().ListModels(ctx, &azdext.ListModelsRequest{})
if err == nil {
return nil
}
if st, ok := status.FromError(err); ok && st.Code() == codes.Unimplemented {
return exterrors.Compatibility(
exterrors.CodeIncompatibleAzdVersion,
"this version of the azure.ai.agents extension is incompatible with your installed version of azd.",
"upgrade azd to the latest version (https://aka.ms/azd/upgrade) and retry",
)
}
return nil
}
func newInitCommand(rootFlags *rootFlagsDefinition) *cobra.Command {
flags := &initFlags{
rootFlagsDefinition: rootFlags,
}
cmd := &cobra.Command{
Use: "init [-m <manifest pointer>] [--src <source directory>]",
Short: fmt.Sprintf("Initialize a new AI agent project. %s", color.YellowString("(Preview)")),
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
ctx := azdext.WithAccessToken(cmd.Context())
setupDebugLogging(cmd.Flags())
azdClient, err := azdext.NewAzdClient()
if err != nil {
return exterrors.Internal(exterrors.CodeAzdClientFailed, fmt.Sprintf("failed to create azd client: %s", err))
}
defer azdClient.Close()
if err := checkAiModelServiceAvailable(ctx, azdClient); err != nil {
return err
}
// Wait for debugger if AZD_EXT_DEBUG is set
if err := azdext.WaitForDebugger(ctx, azdClient); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, azdext.ErrDebuggerAborted) {
return nil
}
return fmt.Errorf("failed waiting for debugger: %w", err)
}
var httpClient = &http.Client{
Timeout: 30 * time.Second,
}
if flags.manifestPointer != "" {
azureContext, projectConfig, environment, err := ensureAzureContext(ctx, flags, azdClient)
if err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
credential, err := azidentity.NewAzureDeveloperCLICredential(&azidentity.AzureDeveloperCLICredentialOptions{
TenantID: azureContext.Scope.TenantId,
AdditionallyAllowedTenants: []string{"*"},
})
if err != nil {
return exterrors.Auth(
exterrors.CodeCredentialCreationFailed,
fmt.Sprintf("failed to create Azure credential: %s", err),
"run 'azd auth login' to authenticate",
)
}
console := input.NewConsole(
false, // noPrompt
true, // isTerminal
input.Writers{Output: os.Stdout},
input.ConsoleHandles{
Stderr: os.Stderr,
Stdin: os.Stdin,
Stdout: os.Stdout,
},
nil, // formatter
nil, // externalPromptCfg
)
action := &InitAction{
azdClient: azdClient,
// azureClient: azure.NewAzureClient(credential),
azureContext: azureContext,
// composedResources: getComposedResourcesResponse.Resources,
console: console,
credential: credential,
projectConfig: projectConfig,
environment: environment,
flags: flags,
httpClient: httpClient,
}
if err := action.Run(ctx); err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
} else {
// No manifest provided - prompt user for init mode
initMode, err := promptInitMode(ctx, azdClient)
if err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
switch initMode {
case initModeTemplate:
// User chose to start from a template - select one
selectedTemplate, err := promptAgentTemplate(ctx, azdClient, httpClient)
if err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
switch selectedTemplate.EffectiveType() {
case TemplateTypeAzd:
// Full azd template - dispatch azd init -t <repo>
initArgs := []string{"init", "-t", selectedTemplate.Source}
if flags.env != "" {
initArgs = append(initArgs, "--environment", flags.env)
} else {
cwd, err := os.Getwd()
if err == nil {
sanitizedDirectoryName := sanitizeAgentName(filepath.Base(cwd))
initArgs = append(initArgs, "--environment", sanitizedDirectoryName+"-dev")
}
}
workflow := &azdext.Workflow{
Name: "init",
Steps: []*azdext.WorkflowStep{
{Command: &azdext.WorkflowCommand{Args: initArgs}},
},
}
_, err := azdClient.Workflow().Run(ctx, &azdext.RunWorkflowRequest{
Workflow: workflow,
})
if err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return exterrors.Dependency(
exterrors.CodeProjectInitFailed,
fmt.Sprintf("failed to initialize project from template: %s", err),
"",
)
}
fmt.Printf("\nProject initialized from template: %s\n", selectedTemplate.Title)
default:
// Agent manifest template - use existing -m flow
flags.manifestPointer = selectedTemplate.Source
azureContext, projectConfig, environment, err := ensureAzureContext(ctx, flags, azdClient)
if err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
credential, err := azidentity.NewAzureDeveloperCLICredential(&azidentity.AzureDeveloperCLICredentialOptions{
TenantID: azureContext.Scope.TenantId,
AdditionallyAllowedTenants: []string{"*"},
})
if err != nil {
return exterrors.Auth(
exterrors.CodeCredentialCreationFailed,
fmt.Sprintf("failed to create Azure credential: %s", err),
"run 'azd auth login' to authenticate",
)
}
console := input.NewConsole(
false, // noPrompt
true, // isTerminal
input.Writers{Output: os.Stdout},
input.ConsoleHandles{
Stderr: os.Stderr,
Stdin: os.Stdin,
Stdout: os.Stdout,
},
nil, // formatter
nil, // externalPromptCfg
)
action := &InitAction{
azdClient: azdClient,
azureContext: azureContext,
console: console,
credential: credential,
projectConfig: projectConfig,
environment: environment,
flags: flags,
httpClient: httpClient,
}
if err := action.Run(ctx); err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
}
default:
// initModeFromCode - use existing code in current directory
action := &InitFromCodeAction{
azdClient: azdClient,
flags: flags,
httpClient: httpClient,
}
if err := action.Run(ctx); err != nil {
if exterrors.IsCancellation(err) {
return exterrors.Cancelled("initialization was cancelled")
}
return err
}
}
}
return nil
},
}
cmd.Flags().StringVarP(&flags.projectResourceId, "project-id", "p", "",
"Existing Microsoft Foundry Project Id to initialize your azd environment with")
cmd.Flags().StringVarP(&flags.modelDeployment, "model-deployment", "d", "",
"Name of an existing model deployment to use from the Foundry project. Only used when paired with an existing Foundry project, either via --project-id or interactive prompts")
cmd.Flags().StringVar(&flags.model, "model", "",
"Name of the AI model to use (e.g., 'gpt-4o'). If not specified, defaults to 'gpt-4.1-mini'. Mutually exclusive with --model-deployment, with --model-deployment being used if both are provided")
cmd.Flags().StringVarP(&flags.manifestPointer, "manifest", "m", "",
"Path or URI to an agent manifest to add to your azd project")
cmd.Flags().StringVarP(&flags.src, "src", "s", "",
"Directory to download the agent definition to (defaults to 'src/<agent-id>')")
cmd.Flags().StringVarP(&flags.host, "host", "", "",
"For container based agents, can override the default host to target a container app instead. Accepted values: 'containerapp'")
cmd.Flags().StringVarP(&flags.env, "environment", "e", "", "The name of the azd environment to use.")
return cmd
}
func (a *InitAction) Run(ctx context.Context) error {
color.Green("Initializing AI agent project...")
fmt.Println()
// If src path is absolute, convert it to relative path compared to the azd project path
if a.flags.src != "" && filepath.IsAbs(a.flags.src) {
projectResponse, err := a.azdClient.Project().Get(ctx, &azdext.EmptyRequest{})
if err != nil {
return fmt.Errorf("failed to get project path: %w", err)
}
relPath, err := filepath.Rel(projectResponse.Project.Path, a.flags.src)
if err != nil {
return fmt.Errorf("failed to convert src path to relative path: %w", err)
}
a.flags.src = relPath
}
// If --manifest is given
if a.flags.manifestPointer != "" {
// If --project-id is given
if a.flags.projectResourceId != "" {
// projectResourceId is a string of the format
// /subscriptions/[AZURE_SUBSCRIPTION]/resourceGroups/[AZURE_RESOURCE_GROUP]/providers/Microsoft.CognitiveServices/accounts/[AI_ACCOUNT_NAME]/projects/[AI_PROJECT_NAME]
// extract each of those fields from the string, issue an error if it doesn't match the format
fmt.Println("Setting up your azd environment to use the provided Microsoft Foundry project resource ID...")
if err := a.parseAndSetProjectResourceId(ctx); err != nil {
return fmt.Errorf("failed to parse project resource ID: %w", err)
}
color.Green("\nYour azd environment has been initialized to use your existing Microsoft Foundry project.")
}
// Validate that the manifest pointer is either a valid URL or existing file path
isValidURL := false
isValidFile := false
if a.flags.host != "" && a.flags.host != "containerapp" {
return exterrors.Validation(
exterrors.CodeUnsupportedHost,
fmt.Sprintf("unsupported host value: '%s' is not supported", a.flags.host),
"use '--host containerapp' or omit '--host'",
)
}
if _, err := url.ParseRequestURI(a.flags.manifestPointer); err == nil {
isValidURL = true
} else if _, fileErr := os.Stat(a.flags.manifestPointer); fileErr == nil {
isValidFile = true
}
if !isValidURL && !isValidFile {
return exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("agent manifest pointer is invalid: '%s' is neither a valid URI nor an existing file path", a.flags.manifestPointer),
"provide a valid URL or an existing local agent.yaml/agent.yml path",
)
}
// Download/read agent.yaml file from the provided URI or file path and save it to project's "agents" directory
agentManifest, targetDir, err := a.downloadAgentYaml(ctx, a.flags.manifestPointer, a.flags.src)
if err != nil {
return fmt.Errorf("downloading agent.yaml: %w", err)
}
// Add the agent to the azd project (azure.yaml) services
if err := a.addToProject(ctx, targetDir, agentManifest, a.flags.host); err != nil {
return fmt.Errorf("failed to add agent to azure.yaml: %w", err)
}
color.Green("\nAI agent definition added to your azd project successfully!")
}
return nil
}
func ensureProject(ctx context.Context, flags *initFlags, azdClient *azdext.AzdClient) (*azdext.ProjectConfig, error) {
projectResponse, err := azdClient.Project().Get(ctx, &azdext.EmptyRequest{})
if err != nil {
fmt.Println("Let's get your project initialized.")
// Environment creation is handled separately in ensureEnvironment
initArgs := []string{"init", "-t", "Azure-Samples/azd-ai-starter-basic"}
if flags.env != "" {
initArgs = append(initArgs, "--environment", flags.env)
} else {
cwd, err := os.Getwd()
if err == nil {
sanitizedDirectoryName := sanitizeAgentName(filepath.Base(cwd))
initArgs = append(initArgs, "--environment", sanitizedDirectoryName+"-dev")
}
}
// We don't have a project yet
// Dispatch a workflow to init the project
workflow := &azdext.Workflow{
Name: "init",
Steps: []*azdext.WorkflowStep{
{Command: &azdext.WorkflowCommand{Args: initArgs}},
},
}
_, err := azdClient.Workflow().Run(ctx, &azdext.RunWorkflowRequest{
Workflow: workflow,
})
if err != nil {
if exterrors.IsCancellation(err) {
return nil, exterrors.Cancelled("project initialization was cancelled")
}
return nil, exterrors.Dependency(
exterrors.CodeProjectInitFailed,
fmt.Sprintf("failed to initialize project: %s", err),
"",
)
}
projectResponse, err = azdClient.Project().Get(ctx, &azdext.EmptyRequest{})
if err != nil {
return nil, exterrors.Dependency(
exterrors.CodeProjectNotFound,
fmt.Sprintf("failed to get project after initialization: %s", err),
"",
)
}
fmt.Println()
}
if projectResponse.Project == nil {
return nil, exterrors.Dependency(
exterrors.CodeProjectNotFound,
"project not found",
"",
)
}
return projectResponse.Project, nil
}
func getExistingEnvironment(ctx context.Context, flags *initFlags, azdClient *azdext.AzdClient) *azdext.Environment {
var env *azdext.Environment
if flags.env == "" {
if envResponse, err := azdClient.Environment().GetCurrent(ctx, &azdext.EmptyRequest{}); err == nil {
env = envResponse.Environment
}
} else {
if envResponse, err := azdClient.Environment().Get(ctx, &azdext.GetEnvironmentRequest{
Name: flags.env,
}); err == nil {
env = envResponse.Environment
}
}
return env
}
func ensureEnvironment(ctx context.Context, flags *initFlags, azdClient *azdext.AzdClient) (*azdext.Environment, error) {
var foundryProject *FoundryProject
var foundryProjectLocation string
if flags.projectResourceId != "" {
var err error
foundryProject, err = extractProjectDetails(flags.projectResourceId)
if err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidProjectResourceId,
fmt.Sprintf("failed to parse Microsoft Foundry project ID: %s", err),
"provide a valid project resource ID in the format /subscriptions/.../providers/Microsoft.CognitiveServices/accounts/.../projects/...",
)
}
// Get the tenant ID
tenantResponse, err := azdClient.Account().LookupTenant(ctx, &azdext.LookupTenantRequest{
SubscriptionId: foundryProject.SubscriptionId,
})
if err != nil {
return nil, exterrors.Auth(
exterrors.CodeTenantLookupFailed,
fmt.Sprintf("failed to get tenant ID for subscription %s: %s", foundryProject.SubscriptionId, err),
"verify your Azure login with 'azd auth login'",
)
}
credential, err := azidentity.NewAzureDeveloperCLICredential(&azidentity.AzureDeveloperCLICredentialOptions{
TenantID: tenantResponse.TenantId,
AdditionallyAllowedTenants: []string{"*"},
})
if err != nil {
return nil, exterrors.Auth(
exterrors.CodeCredentialCreationFailed,
fmt.Sprintf("failed to create Azure credential: %s", err),
"run 'azd auth login' to authenticate",
)
}
// Create Cognitive Services Projects client
projectsClient, err := armcognitiveservices.NewProjectsClient(foundryProject.SubscriptionId, credential, azure.NewArmClientOptions())
if err != nil {
return nil, exterrors.Internal(exterrors.CodeCognitiveServicesClientFailed, fmt.Sprintf("failed to create Cognitive Services Projects client: %s", err))
}
// Get the Microsoft Foundry project
projectResp, err := projectsClient.Get(ctx, foundryProject.ResourceGroupName, foundryProject.AiAccountName, foundryProject.AiProjectName, nil)
if err != nil {
return nil, exterrors.ServiceFromAzure(err, exterrors.OpGetFoundryProject)
}
foundryProjectLocation = *projectResp.Location
}
// Get specified or current environment if it exists
existingEnv := getExistingEnvironment(ctx, flags, azdClient)
if existingEnv == nil {
// Dispatch `azd env new` to create a new environment with interactive flow
fmt.Println("Lets create a new default azd environment for your project.")
envArgs := []string{"env", "new"}
if flags.env != "" {
envArgs = append(envArgs, flags.env)
}
if flags.projectResourceId != "" {
envArgs = append(envArgs, "--subscription", foundryProject.SubscriptionId)
envArgs = append(envArgs, "--location", foundryProjectLocation)
}
// Dispatch a workflow to create a new environment
// Handles both interactive and no-prompt flows
workflow := &azdext.Workflow{
Name: "env new",
Steps: []*azdext.WorkflowStep{
{Command: &azdext.WorkflowCommand{Args: envArgs}},
},
}
_, err := azdClient.Workflow().Run(ctx, &azdext.RunWorkflowRequest{
Workflow: workflow,
})
if err != nil {
if exterrors.IsCancellation(err) {
return nil, exterrors.Cancelled("environment creation was cancelled")
}
return nil, exterrors.Dependency(
exterrors.CodeEnvironmentCreationFailed,
fmt.Sprintf("failed to create new azd environment: %s", err),
"run 'azd env new' manually to create an environment",
)
}
// Re-fetch the environment after creation
existingEnv = getExistingEnvironment(ctx, flags, azdClient)
if existingEnv == nil {
return nil, exterrors.Dependency(
exterrors.CodeEnvironmentNotFound,
"azd environment not found after creation",
"run 'azd env new' to create an environment and try again",
)
}
} else if flags.projectResourceId != "" {
currentSubscription, err := azdClient.Environment().GetValue(ctx, &azdext.GetEnvRequest{
EnvName: existingEnv.Name,
Key: "AZURE_SUBSCRIPTION_ID",
})
if err != nil {
return nil, fmt.Errorf("failed to get current AZURE_SUBSCRIPTION_ID from azd environment: %w", err)
}
if currentSubscription.Value == "" {
// Set the subscription ID in the environment
_, err = azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{
EnvName: existingEnv.Name,
Key: "AZURE_SUBSCRIPTION_ID",
Value: foundryProject.SubscriptionId,
})
if err != nil {
return nil, fmt.Errorf("failed to set AZURE_SUBSCRIPTION_ID in azd environment: %w", err)
}
} else if currentSubscription.Value != foundryProject.SubscriptionId {
return nil, exterrors.Validation(
exterrors.CodeSubscriptionMismatch,
fmt.Sprintf("subscription ID mismatch: environment has %s but project uses %s", currentSubscription.Value, foundryProject.SubscriptionId),
"update or recreate your environment with 'azd env new'",
)
}
// Resolve and set the tenant ID for the subscription so credentials are scoped correctly
currentTenant, err := azdClient.Environment().GetValue(ctx, &azdext.GetEnvRequest{
EnvName: existingEnv.Name,
Key: "AZURE_TENANT_ID",
})
if err != nil {
return nil, fmt.Errorf("failed to get current AZURE_TENANT_ID from azd environment: %w", err)
}
tenantResp, err := azdClient.Account().LookupTenant(ctx, &azdext.LookupTenantRequest{
SubscriptionId: foundryProject.SubscriptionId,
})
if err != nil {
return nil, exterrors.Auth(
exterrors.CodeTenantLookupFailed,
fmt.Sprintf("failed to lookup tenant for subscription %s: %s", foundryProject.SubscriptionId, err),
"verify your Azure login with 'azd auth login'",
)
}
if currentTenant.Value == "" {
_, err = azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{
EnvName: existingEnv.Name,
Key: "AZURE_TENANT_ID",
Value: tenantResp.TenantId,
})
if err != nil {
return nil, fmt.Errorf("failed to set AZURE_TENANT_ID in azd environment: %w", err)
}
} else if currentTenant.Value != tenantResp.TenantId {
return nil, exterrors.Validation(
exterrors.CodeTenantMismatch,
fmt.Sprintf("tenant ID mismatch: environment has %s but project uses %s", currentTenant.Value, tenantResp.TenantId),
"update or recreate your environment with 'azd env new'",
)
}
// Get current location from environment
currentLocation, err := azdClient.Environment().GetValue(ctx, &azdext.GetEnvRequest{
EnvName: existingEnv.Name,
Key: "AZURE_LOCATION",
})
if err != nil {
return nil, fmt.Errorf("failed to get AZURE_LOCATION from azd environment: %w", err)
}
if currentLocation.Value == "" {
// Set the location in the environment
_, err = azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{
EnvName: existingEnv.Name,
Key: "AZURE_LOCATION",
Value: foundryProjectLocation,
})
if err != nil {
return nil, fmt.Errorf("failed to set AZURE_LOCATION in environment: %w", err)
}
} else if currentLocation.Value != foundryProjectLocation {
return nil, exterrors.Validation(
exterrors.CodeLocationMismatch,
fmt.Sprintf("location mismatch: environment has %s but project uses %s", currentLocation.Value, foundryProjectLocation),
"update or recreate your environment with 'azd env new'",
)
}
}
return existingEnv, nil
}
func ensureAzureContext(
ctx context.Context,
flags *initFlags,
azdClient *azdext.AzdClient,
) (*azdext.AzureContext, *azdext.ProjectConfig, *azdext.Environment, error) {
project, err := ensureProject(ctx, flags, azdClient)
if err != nil {
return nil, nil, nil, err
}
env, err := ensureEnvironment(ctx, flags, azdClient)
if err != nil {
return nil, nil, nil, err
}
envValues, err := azdClient.Environment().GetValues(ctx, &azdext.GetEnvironmentRequest{
Name: env.Name,
})
if err != nil {
return nil, nil, nil, exterrors.Dependency(
exterrors.CodeEnvironmentValuesFailed,
fmt.Sprintf("failed to get environment values: %s", err),
"run 'azd env get-values' to verify environment state",
)
}
envValueMap := make(map[string]string)
for _, value := range envValues.KeyValues {
envValueMap[value.Key] = value.Value
}
azureContext := &azdext.AzureContext{
Scope: &azdext.AzureScope{
TenantId: envValueMap["AZURE_TENANT_ID"],
SubscriptionId: envValueMap["AZURE_SUBSCRIPTION_ID"],
Location: envValueMap["AZURE_LOCATION"],
},
Resources: []string{},
}
if azureContext.Scope.SubscriptionId == "" {
fmt.Print()
fmt.Println("We need to connect to your Azure subscription. This will be the subscription which contains your ")
fmt.Println("Foundry project and where your resources will be provisioned.")
subscriptionResponse, err := azdClient.Prompt().PromptSubscription(ctx, &azdext.PromptSubscriptionRequest{})
if err != nil {
if exterrors.IsCancellation(err) {
return nil, nil, nil, exterrors.Cancelled("subscription selection was cancelled")
}
return nil, nil, nil, exterrors.FromPrompt(err, "failed to prompt for subscription")
}
azureContext.Scope.SubscriptionId = subscriptionResponse.Subscription.Id
azureContext.Scope.TenantId = subscriptionResponse.Subscription.TenantId
// Set the subscription ID in the environment
_, err = azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{
EnvName: env.Name,
Key: "AZURE_TENANT_ID",
Value: azureContext.Scope.TenantId,
})
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to set AZURE_TENANT_ID in environment: %w", err)
}
// Set the tenant ID in the environment
_, err = azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{
EnvName: env.Name,
Key: "AZURE_SUBSCRIPTION_ID",
Value: azureContext.Scope.SubscriptionId,
})
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to set AZURE_SUBSCRIPTION_ID in environment: %w", err)
}
}
if azureContext.Scope.Location == "" {
fmt.Println()
fmt.Println(
"Next, we need to select a default Azure location that will be used as the target for your resources.",
)
locationResponse, err := azdClient.Prompt().PromptLocation(ctx, &azdext.PromptLocationRequest{
AzureContext: azureContext,
})
if err != nil {
if exterrors.IsCancellation(err) {
return nil, nil, nil, exterrors.Cancelled("location selection was cancelled")
}
return nil, nil, nil, exterrors.FromPrompt(err, "failed to prompt for location")
}
azureContext.Scope.Location = locationResponse.Location.Name
// Set the location in the environment
_, err = azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{
EnvName: env.Name,
Key: "AZURE_LOCATION",
Value: azureContext.Scope.Location,
})
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to set AZURE_LOCATION in environment: %w", err)
}
}
return azureContext, project, env, nil
}
type FoundryProject struct {
SubscriptionId string `json:"subscriptionId"`
ResourceGroupName string `json:"resourceGroupName"`
AiAccountName string `json:"aiAccountName"`
AiProjectName string `json:"aiProjectName"`
}
func extractProjectDetails(projectResourceId string) (*FoundryProject, error) {
/// Define the regex pattern for the project resource ID
pattern := `^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/Microsoft\.CognitiveServices/accounts/([^/]+)/projects/([^/]+)$`
regex, err := regexp.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("failed to compile regex pattern: %w", err)
}
matches := regex.FindStringSubmatch(projectResourceId)
if matches == nil || len(matches) != 5 {
return nil, fmt.Errorf(
"the given Microsoft Foundry project ID does not match expected format: " +
"/subscriptions/[SUBSCRIPTION_ID]/resourceGroups/[RESOURCE_GROUP]/providers/" +
"Microsoft.CognitiveServices/accounts/[ACCOUNT_NAME]/projects/[PROJECT_NAME]",
)
}
// Extract the components
return &FoundryProject{
SubscriptionId: matches[1],
ResourceGroupName: matches[2],
AiAccountName: matches[3],
AiProjectName: matches[4],
}, nil
}
func (a *InitAction) parseAndSetProjectResourceId(ctx context.Context) error {
foundryProject, err := extractProjectDetails(a.flags.projectResourceId)
if err != nil {
return fmt.Errorf("extracting project details: %w", err)
}
if err := a.setEnvVar(ctx, "AZURE_AI_PROJECT_ID", a.flags.projectResourceId); err != nil {
return err
}
// Set the extracted values as environment variables
if err := a.setEnvVar(ctx, "AZURE_RESOURCE_GROUP", foundryProject.ResourceGroupName); err != nil {
return err
}
if err := a.setEnvVar(ctx, "AZURE_AI_ACCOUNT_NAME", foundryProject.AiAccountName); err != nil {
return err
}
if err := a.setEnvVar(ctx, "AZURE_AI_PROJECT_NAME", foundryProject.AiProjectName); err != nil {
return err
}
// Set the Microsoft Foundry endpoint URL
aiFoundryEndpoint := fmt.Sprintf("https://%s.services.ai.azure.com/api/projects/%s", foundryProject.AiAccountName, foundryProject.AiProjectName)
if err := a.setEnvVar(ctx, "AZURE_AI_PROJECT_ENDPOINT", aiFoundryEndpoint); err != nil {
return err
}
aoaiEndpoint := fmt.Sprintf("https://%s.openai.azure.com/", foundryProject.AiAccountName)
if err := a.setEnvVar(ctx, "AZURE_OPENAI_ENDPOINT", aoaiEndpoint); err != nil {
return err
}
// Create FoundryProjectsClient and get connections
foundryClient := azure.NewFoundryProjectsClient(foundryProject.AiAccountName, foundryProject.AiProjectName, a.credential)
connections, err := foundryClient.GetAllConnections(ctx)
if err != nil {
fmt.Printf("Could not get Microsoft Foundry project connections to initialize AZURE_CONTAINER_REGISTRY_ENDPOINT: %v. Please set this environment variable manually.\n", err)
} else {
// Filter connections by ContainerRegistry type
var acrConnections []azure.Connection
var appInsightsConnections []azure.Connection
for _, conn := range connections {
switch conn.Type {
case azure.ConnectionTypeContainerRegistry:
acrConnections = append(acrConnections, conn)
case azure.ConnectionTypeAppInsights:
connWithCreds, err := foundryClient.GetConnectionWithCredentials(ctx, conn.Name)
if err != nil {
fmt.Printf("Could not get full details for Application Insights connection '%s': %v\n", conn.Name, err)
continue
}
if connWithCreds != nil {
conn = *connWithCreds
}
appInsightsConnections = append(appInsightsConnections, conn)
}
}
if len(acrConnections) == 0 {
fmt.Println(output.WithWarningFormat(
"Agent deployment prerequisites not satisfied. To deploy this agent, you will need to " +
"provision an Azure Container Registry (ACR) and grant the required permissions. " +
"You can either do this manually before deployment, or use an infrastructure template. " +
"See aka.ms/azdaiagent/docs for details."))
resp, err := a.azdClient.Prompt().Prompt(ctx, &azdext.PromptRequest{
Options: &azdext.PromptOptions{
Message: "If you have an ACR that you want to use with this agent, enter the azurecr.io endpoint for the ACR. " +
"If you plan to provision one through the `azd provision` or `azd up` flow, leave blank.",
IgnoreHintKeys: true,
},
})
if err != nil {
return fmt.Errorf("prompting for ACR endpoint: %w", err)
}
if resp.Value != "" {
if err := a.setEnvVar(ctx, "AZURE_CONTAINER_REGISTRY_ENDPOINT", resp.Value); err != nil {
return err
}
}
} else {
var selectedConnection *azure.Connection
if len(acrConnections) == 1 {
selectedConnection = &acrConnections[0]
fmt.Printf("Using container registry connection: %s (%s)\n", selectedConnection.Name, selectedConnection.Target)
} else {
// Multiple connections found, prompt user to select
fmt.Printf("Found %d container registry connections:\n", len(acrConnections))
choices := make([]*azdext.SelectChoice, len(acrConnections))
for i, conn := range acrConnections {
choices[i] = &azdext.SelectChoice{
Label: conn.Name,
Value: fmt.Sprintf("%d", i),
}
}
defaultIndex := int32(0)
selectResp, err := a.azdClient.Prompt().Select(ctx, &azdext.SelectRequest{
Options: &azdext.SelectOptions{
Message: "Select a container registry connection to use for this agent",
Choices: choices,
SelectedIndex: &defaultIndex,
},
})
if err != nil {
fmt.Printf("failed to prompt for connection selection: %v\n", err)
} else {
selectedConnection = &acrConnections[int(*selectResp.Value)]
}
}
if err := a.setEnvVar(ctx, "AZURE_CONTAINER_REGISTRY_ENDPOINT", selectedConnection.Target); err != nil {
return err
}
}
// Handle App Insights connections
if len(appInsightsConnections) == 0 {
fmt.Println(output.WithWarningFormat(
"No Application Insights connection found. To enable telemetry for this agent, you will need to " +
"provision an Application Insights resource and grant the required permissions. " +
"You can either do this manually before deployment, or use an infrastructure template. " +
"See aka.ms/azdaiagent/docs for details."))
resp, err := a.azdClient.Prompt().Prompt(ctx, &azdext.PromptRequest{
Options: &azdext.PromptOptions{
Message: "If you have an Application Insights resource that you want to use with this agent, enter the connection string. " +
"If you plan to provision one through the `azd provision` or `azd up` flow, leave blank.",
IgnoreHintKeys: true,
},
})
if err != nil {
return fmt.Errorf("prompting for Application Insights connection string: %w", err)
}
if resp.Value != "" {
if err := a.setEnvVar(ctx, "APPLICATIONINSIGHTS_CONNECTION_STRING", resp.Value); err != nil {
return err
}
}
} else {
var selectedConnection *azure.Connection