forked from Azure/azure-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice_target_agent.go
More file actions
1321 lines (1155 loc) · 43.5 KB
/
service_target_agent.go
File metadata and controls
1321 lines (1155 loc) · 43.5 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 project
import (
"context"
"encoding/base64"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"azureaiagent/internal/exterrors"
"azureaiagent/internal/pkg/agents/agent_api"
"azureaiagent/internal/pkg/agents/agent_yaml"
"azureaiagent/internal/pkg/azure"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"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/output"
"github.com/braydonk/yaml"
"github.com/drone/envsubst"
"github.com/fatih/color"
"github.com/google/uuid"
)
// Reference implementation
// Ensure AgentServiceTargetProvider implements ServiceTargetProvider interface
var _ azdext.ServiceTargetProvider = &AgentServiceTargetProvider{}
// AgentServiceTargetProvider is a minimal implementation of ServiceTargetProvider for demonstration
type AgentServiceTargetProvider struct {
azdClient *azdext.AzdClient
serviceConfig *azdext.ServiceConfig
agentDefinitionPath string
credential *azidentity.AzureDeveloperCLICredential
tenantId string
env *azdext.Environment
foundryProject *arm.ResourceID
}
// NewAgentServiceTargetProvider creates a new AgentServiceTargetProvider instance
func NewAgentServiceTargetProvider(azdClient *azdext.AzdClient) azdext.ServiceTargetProvider {
return &AgentServiceTargetProvider{
azdClient: azdClient,
}
}
// Initialize initializes the service target by looking for the agent definition file
func (p *AgentServiceTargetProvider) Initialize(ctx context.Context, serviceConfig *azdext.ServiceConfig) error {
if p.agentDefinitionPath != "" {
// Already initialized
return nil
}
p.serviceConfig = serviceConfig
proj, err := p.azdClient.Project().Get(ctx, nil)
if err != nil {
return exterrors.Dependency(
exterrors.CodeProjectNotFound,
fmt.Sprintf("failed to get project: %s", err),
"run 'azd init' to initialize your project",
)
}
servicePath := serviceConfig.RelativePath
fullPath := filepath.Join(proj.Project.Path, servicePath)
// Get and store environment
azdEnvClient := p.azdClient.Environment()
currEnv, err := azdEnvClient.GetCurrent(ctx, nil)
if err != nil {
return exterrors.Dependency(
exterrors.CodeEnvironmentNotFound,
fmt.Sprintf("failed to get current environment: %s", err),
"run 'azd env new' to create an environment",
)
}
p.env = currEnv.Environment
// Get subscription ID from environment
resp, err := azdEnvClient.GetValue(ctx, &azdext.GetEnvRequest{
EnvName: p.env.Name,
Key: "AZURE_SUBSCRIPTION_ID",
})
if err != nil {
return fmt.Errorf("failed to get AZURE_SUBSCRIPTION_ID: %w", err)
}
subscriptionId := resp.Value
if subscriptionId == "" {
return exterrors.Dependency(
exterrors.CodeMissingAzureSubscription,
"AZURE_SUBSCRIPTION_ID is required: environment variable was not found in the current azd environment",
"run 'azd env get-values' to verify environment values, or initialize/project-bind "+
"with 'azd ai agent init --project-id ...'",
)
}
// Get the tenant ID
tenantResponse, err := p.azdClient.Account().LookupTenant(ctx, &azdext.LookupTenantRequest{
SubscriptionId: subscriptionId,
})
if err != nil {
return exterrors.Auth(
exterrors.CodeTenantLookupFailed,
fmt.Sprintf("failed to get tenant ID for subscription %s: %s", subscriptionId, err),
"verify your Azure login with 'azd auth login' and that you have access to this subscription",
)
}
p.tenantId = tenantResponse.TenantId
// Create Azure credential
cred, err := azidentity.NewAzureDeveloperCLICredential(&azidentity.AzureDeveloperCLICredentialOptions{
TenantID: p.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",
)
}
p.credential = cred
fmt.Fprintf(os.Stderr, "Project path: %s, Service path: %s\n", proj.Project.Path, fullPath)
// Check if user has specified agent definition path via environment variable
if envPath := os.Getenv("AGENT_DEFINITION_PATH"); envPath != "" {
// Verify the file exists and has correct extension
//nolint:gosec // env path is an explicit user override; existence check is intentional
if _, err := os.Stat(envPath); os.IsNotExist(err) {
return exterrors.Validation(
exterrors.CodeAgentDefinitionNotFound,
fmt.Sprintf("agent definition file specified in AGENT_DEFINITION_PATH does not exist: %s", envPath),
"verify the path set in AGENT_DEFINITION_PATH points to a valid agent.yaml file",
)
}
ext := strings.ToLower(filepath.Ext(envPath))
if ext != ".yaml" && ext != ".yml" {
return exterrors.Validation(
exterrors.CodeAgentDefinitionNotFound,
fmt.Sprintf("agent definition file must be a YAML file (.yaml or .yml), got: %s", envPath),
"provide a file with .yaml or .yml extension",
)
}
p.agentDefinitionPath = envPath
fmt.Printf("Using agent definition from environment variable: %s\n", color.New(color.FgHiGreen).Sprint(envPath))
return nil
}
// Look for agent.yaml or agent.yml in the service directory root
agentYamlPath := filepath.Join(fullPath, "agent.yaml")
agentYmlPath := filepath.Join(fullPath, "agent.yml")
if _, err := os.Stat(agentYamlPath); err == nil {
p.agentDefinitionPath = agentYamlPath
fmt.Printf("Using agent definition: %s\n", color.New(color.FgHiGreen).Sprint(agentYamlPath))
return nil
}
if _, err := os.Stat(agentYmlPath); err == nil {
p.agentDefinitionPath = agentYmlPath
fmt.Printf("Using agent definition: %s\n", color.New(color.FgHiGreen).Sprint(agentYmlPath))
return nil
}
return exterrors.Dependency(
exterrors.CodeAgentDefinitionNotFound,
fmt.Sprintf("agent definition file not found: no agent.yaml or agent.yml found in %s", fullPath),
"add an agent.yaml/agent.yml file to the service directory or set AGENT_DEFINITION_PATH",
)
}
// getServiceKey converts a service name into a standardized environment variable key format
func (p *AgentServiceTargetProvider) getServiceKey(serviceName string) string {
serviceKey := strings.ReplaceAll(serviceName, " ", "_")
serviceKey = strings.ReplaceAll(serviceKey, "-", "_")
return strings.ToUpper(serviceKey)
}
// Endpoints returns endpoints exposed by the agent service
func (p *AgentServiceTargetProvider) Endpoints(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
targetResource *azdext.TargetResource,
) ([]string, error) {
// Get all environment values
resp, err := p.azdClient.Environment().GetValues(ctx, &azdext.GetEnvironmentRequest{
Name: p.env.Name,
})
if err != nil {
return nil, exterrors.Dependency(
exterrors.CodeEnvironmentValuesFailed,
fmt.Sprintf("failed to get environment values: %s", err),
"run 'azd env get-values' to verify environment state",
)
}
azdEnv := make(map[string]string, len(resp.KeyValues))
for _, kval := range resp.KeyValues {
azdEnv[kval.Key] = kval.Value
}
// Check if required environment variables are set
if azdEnv["AZURE_AI_PROJECT_ENDPOINT"] == "" {
return nil, exterrors.Dependency(
exterrors.CodeMissingAiProjectEndpoint,
"AZURE_AI_PROJECT_ENDPOINT is required: environment variable was not found in the current azd environment",
"run 'azd provision' or connect to an existing project via 'azd ai agent init --project-id <resource-id>'",
)
}
serviceKey := p.getServiceKey(serviceConfig.Name)
agentNameKey := fmt.Sprintf("AGENT_%s_NAME", serviceKey)
agentVersionKey := fmt.Sprintf("AGENT_%s_VERSION", serviceKey)
if azdEnv[agentNameKey] == "" || azdEnv[agentVersionKey] == "" {
return nil, exterrors.Dependency(
exterrors.CodeMissingAgentEnvVars,
fmt.Sprintf("%s and %s environment variables are required", agentNameKey, agentVersionKey),
"run 'azd deploy' to deploy the agent and set these variables",
)
}
endpoint := p.agentEndpoint(azdEnv["AZURE_AI_PROJECT_ENDPOINT"], azdEnv[agentNameKey], azdEnv[agentVersionKey])
return []string{endpoint}, nil
}
// GetTargetResource returns a custom target resource for the agent service
func (p *AgentServiceTargetProvider) GetTargetResource(
ctx context.Context,
subscriptionId string,
serviceConfig *azdext.ServiceConfig,
defaultResolver func() (*azdext.TargetResource, error),
) (*azdext.TargetResource, error) {
// Ensure Foundry project is loaded
if err := p.ensureFoundryProject(ctx); err != nil {
return nil, err
}
// Extract account name from parent resource ID
if p.foundryProject.Parent == nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidFoundryResourceId,
"invalid resource ID: missing parent account",
"verify the AZURE_AI_PROJECT_ID is a valid Microsoft Foundry project resource ID",
)
}
accountName := p.foundryProject.Parent.Name
projectName := p.foundryProject.Name
// Create Cognitive Services Projects client
projectsClient, err := armcognitiveservices.NewProjectsClient(
p.foundryProject.SubscriptionID, p.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, p.foundryProject.ResourceGroupName, accountName, projectName, nil)
if err != nil {
return nil, exterrors.ServiceFromAzure(err, exterrors.OpGetFoundryProject)
}
// Construct the target resource
targetResource := &azdext.TargetResource{
SubscriptionId: p.foundryProject.SubscriptionID,
ResourceGroupName: p.foundryProject.ResourceGroupName,
ResourceName: projectName,
ResourceType: "Microsoft.CognitiveServices/accounts/projects",
Metadata: map[string]string{
"accountName": accountName,
"projectName": projectName,
},
}
// Add location if available
if projectResp.Location != nil {
targetResource.Metadata["location"] = *projectResp.Location
}
return targetResource, nil
}
// Package performs packaging for the agent service
func (p *AgentServiceTargetProvider) Package(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
serviceContext *azdext.ServiceContext,
progress azdext.ProgressReporter,
) (*azdext.ServicePackageResult, error) {
if !p.isContainerAgent() {
return &azdext.ServicePackageResult{}, nil
}
var packageArtifact *azdext.Artifact
var newArtifacts []*azdext.Artifact
progress("Packaging container")
for _, artifact := range serviceContext.Package {
if artifact.Kind == azdext.ArtifactKind_ARTIFACT_KIND_CONTAINER {
packageArtifact = artifact
break
}
}
if packageArtifact == nil {
var buildArtifact *azdext.Artifact
for _, artifact := range serviceContext.Build {
if artifact.Kind == azdext.ArtifactKind_ARTIFACT_KIND_CONTAINER {
buildArtifact = artifact
break
}
}
if buildArtifact == nil {
buildResponse, err := p.azdClient.
Container().
Build(ctx, &azdext.ContainerBuildRequest{
ServiceName: serviceConfig.Name,
ServiceContext: serviceContext,
})
if err != nil {
return nil, exterrors.Internal(exterrors.OpContainerBuild, fmt.Sprintf("container build failed: %s", err))
}
serviceContext.Build = append(serviceContext.Build, buildResponse.Result.Artifacts...)
}
packageResponse, err := p.azdClient.
Container().
Package(ctx, &azdext.ContainerPackageRequest{
ServiceName: serviceConfig.Name,
ServiceContext: serviceContext,
})
if err != nil {
return nil, exterrors.Internal(exterrors.OpContainerPackage, fmt.Sprintf("container package failed: %s", err))
}
newArtifacts = append(newArtifacts, packageResponse.Result.Artifacts...)
}
return &azdext.ServicePackageResult{
Artifacts: newArtifacts,
}, nil
}
// Publish performs the publish operation for the agent service
func (p *AgentServiceTargetProvider) Publish(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
serviceContext *azdext.ServiceContext,
targetResource *azdext.TargetResource,
publishOptions *azdext.PublishOptions,
progress azdext.ProgressReporter,
) (*azdext.ServicePublishResult, error) {
if !p.isContainerAgent() {
return &azdext.ServicePublishResult{}, nil
}
progress("Publishing container")
publishResponse, err := p.azdClient.
Container().
Publish(ctx, &azdext.ContainerPublishRequest{
ServiceName: serviceConfig.Name,
ServiceContext: serviceContext,
})
if err != nil {
return nil, exterrors.Internal(exterrors.OpContainerPublish, fmt.Sprintf("container publish failed: %s", err))
}
return &azdext.ServicePublishResult{
Artifacts: publishResponse.Result.Artifacts,
}, nil
}
// Deploy performs the deployment operation for the agent service
func (p *AgentServiceTargetProvider) Deploy(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
serviceContext *azdext.ServiceContext,
targetResource *azdext.TargetResource,
progress azdext.ProgressReporter,
) (*azdext.ServiceDeployResult, error) {
// Ensure Foundry project is loaded
if err := p.ensureFoundryProject(ctx); err != nil {
return nil, err
}
// Get environment variables from azd
resp, err := p.azdClient.Environment().GetValues(ctx, &azdext.GetEnvironmentRequest{
Name: p.env.Name,
})
if err != nil {
return nil, exterrors.Dependency(
exterrors.CodeEnvironmentValuesFailed,
fmt.Sprintf("failed to get environment values: %s", err),
"run 'azd env get-values' to verify environment state",
)
}
azdEnv := make(map[string]string, len(resp.KeyValues))
for _, kval := range resp.KeyValues {
azdEnv[kval.Key] = kval.Value
}
var serviceTargetConfig *ServiceTargetAgentConfig
if err := UnmarshalStruct(serviceConfig.Config, &serviceTargetConfig); err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidServiceConfig,
fmt.Sprintf("failed to parse service target config: %s", err),
"check the service configuration in azure.yaml",
)
}
if serviceTargetConfig != nil {
fmt.Println("Loaded custom service target configuration")
}
// Load and validate the agent manifest
data, err := os.ReadFile(p.agentDefinitionPath)
if err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("failed to read agent manifest file: %s", err),
"verify the agent.yaml file exists and is readable",
)
}
err = agent_yaml.ValidateAgentDefinition(data)
if err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("agent.yaml is not valid: %s", err),
"fix the agent.yaml file according to the schema",
)
}
var genericTemplate map[string]interface{}
if err := yaml.Unmarshal(data, &genericTemplate); err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("YAML content is not valid for deploy: %s", err),
"verify the agent.yaml has valid YAML syntax",
)
}
kind, ok := genericTemplate["kind"].(string)
if !ok {
return nil, exterrors.Validation(
exterrors.CodeMissingAgentKind,
"kind field is missing or not a valid string in agent.yaml",
"add a valid 'kind' field (e.g., 'prompt' or 'hosted') to agent.yaml",
)
}
switch kind {
case string(agent_yaml.AgentKindPrompt):
var agentDef agent_yaml.PromptAgent
if err := yaml.Unmarshal(data, &agentDef); err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("YAML content is not valid for prompt agent deploy: %s", err),
"fix the agent.yaml to match the prompt agent schema",
)
}
return p.deployPromptAgent(ctx, serviceConfig, agentDef, azdEnv)
case string(agent_yaml.AgentKindHosted):
var agentDef agent_yaml.ContainerAgent
if err := yaml.Unmarshal(data, &agentDef); err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("YAML content is not valid for hosted agent deploy: %s", err),
"fix the agent.yaml to match the hosted agent schema",
)
}
return p.deployHostedAgent(ctx, serviceConfig, serviceContext, progress, agentDef, azdEnv)
default:
return nil, exterrors.Validation(
exterrors.CodeUnsupportedAgentKind,
fmt.Sprintf("unsupported agent kind: %s", kind),
"use a supported kind: 'prompt' or 'hosted'",
)
}
}
func (p *AgentServiceTargetProvider) isContainerAgent() bool {
// Load and validate the agent manifest
data, err := os.ReadFile(p.agentDefinitionPath)
if err != nil {
return false
}
err = agent_yaml.ValidateAgentDefinition(data)
if err != nil {
return false
}
var genericTemplate map[string]interface{}
if err := yaml.Unmarshal(data, &genericTemplate); err != nil {
return false
}
kind, ok := genericTemplate["kind"].(string)
if !ok {
return false
}
return kind == string(agent_yaml.AgentKindHosted)
}
// deployPromptAgent handles deployment of prompt-based agents
func (p *AgentServiceTargetProvider) deployPromptAgent(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
agentDef agent_yaml.PromptAgent,
azdEnv map[string]string,
) (*azdext.ServiceDeployResult, error) {
// Check if environment variable is set
if azdEnv["AZURE_AI_PROJECT_ENDPOINT"] == "" {
return nil, exterrors.Dependency(
exterrors.CodeMissingAiProjectEndpoint,
"AZURE_AI_PROJECT_ENDPOINT is required: environment variable was not found in the current azd environment",
"run 'azd provision' or connect to an existing project via 'azd ai agent init --project-id <resource-id>'",
)
}
fmt.Fprintf(os.Stderr, "Deploying Prompt Agent\n")
fmt.Fprintf(os.Stderr, "======================\n")
fmt.Fprintf(os.Stderr, "Loaded configuration from: %s\n", p.agentDefinitionPath)
fmt.Fprintf(os.Stderr, "Using endpoint: %s\n", azdEnv["AZURE_AI_PROJECT_ENDPOINT"])
fmt.Fprintf(os.Stderr, "Agent Name: %s\n", agentDef.Name)
// Create agent request (no image URL needed for prompt agents)
request, err := agent_yaml.CreateAgentAPIRequestFromDefinition(agentDef)
if err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentRequest,
fmt.Sprintf("failed to create agent request from definition: %s", err),
"verify the agent.yaml definition is correct",
)
}
// Display agent information
p.displayAgentInfo(request)
// Create and deploy agent
agentVersionResponse, err := p.createAgent(ctx, request, azdEnv)
if err != nil {
return nil, err
}
// Register agent info in environment
err = p.registerAgentEnvironmentVariables(ctx, azdEnv, serviceConfig, agentVersionResponse)
if err != nil {
return nil, err
}
fmt.Fprintf(os.Stderr, "Prompt agent '%s' deployed successfully!\n", agentVersionResponse.Name)
artifacts := p.deployArtifacts(
agentVersionResponse.Name,
agentVersionResponse.Version,
azdEnv["AZURE_AI_PROJECT_ID"],
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
)
return &azdext.ServiceDeployResult{
Artifacts: artifacts,
}, nil
}
// deployHostedAgent handles deployment of hosted container agents
func (p *AgentServiceTargetProvider) deployHostedAgent(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
serviceContext *azdext.ServiceContext,
progress azdext.ProgressReporter,
agentDef agent_yaml.ContainerAgent,
azdEnv map[string]string,
) (*azdext.ServiceDeployResult, error) {
// Check if environment variable is set
if azdEnv["AZURE_AI_PROJECT_ENDPOINT"] == "" {
return nil, exterrors.Dependency(
exterrors.CodeMissingAiProjectEndpoint,
"AZURE_AI_PROJECT_ENDPOINT is required: environment variable was not found in the current azd environment",
"run 'azd provision' or connect to an existing project via 'azd ai agent init --project-id <resource-id>'",
)
}
progress("Deploying hosted agent")
// Step 1: Build container image
var fullImageURL string
for _, artifact := range serviceContext.Publish {
if artifact.Kind == azdext.ArtifactKind_ARTIFACT_KIND_CONTAINER &&
artifact.LocationKind == azdext.LocationKind_LOCATION_KIND_REMOTE {
fullImageURL = artifact.Location
break
}
}
if fullImageURL == "" {
return nil, exterrors.Dependency(
exterrors.CodeMissingPublishedContainer,
"published container artifact not found: no remote container artifact was found in service publish artifacts",
"run 'azd package' and 'azd publish' (or 'azd deploy') to produce container artifacts",
)
}
fmt.Fprintf(os.Stderr, "Loaded configuration from: %s\n", p.agentDefinitionPath)
fmt.Fprintf(os.Stderr, "Using endpoint: %s\n", azdEnv["AZURE_AI_PROJECT_ENDPOINT"])
fmt.Fprintf(os.Stderr, "Agent Name: %s\n", agentDef.Name)
// Step 2: Resolve environment variables from YAML using azd environment values
resolvedEnvVars := make(map[string]string)
if agentDef.EnvironmentVariables != nil {
for _, envVar := range *agentDef.EnvironmentVariables {
resolvedEnvVars[envVar.Name] = p.resolveEnvironmentVariables(envVar.Value, azdEnv)
}
}
// Step 3: Create agent request with image URL and resolved environment variables
var foundryAgentConfig *ServiceTargetAgentConfig
if err := UnmarshalStruct(serviceConfig.Config, &foundryAgentConfig); err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentManifest,
fmt.Sprintf("failed to parse foundry agent config: %s", err),
"check the service configuration in azure.yaml",
)
}
var cpu, memory string
if foundryAgentConfig.Container != nil && foundryAgentConfig.Container.Resources != nil {
cpu = foundryAgentConfig.Container.Resources.Cpu
memory = foundryAgentConfig.Container.Resources.Memory
}
// Build options list starting with required options
options := []agent_yaml.AgentBuildOption{
agent_yaml.WithImageURL(fullImageURL),
agent_yaml.WithEnvironmentVariables(resolvedEnvVars),
}
// Conditionally add CPU and memory options if they're not empty
if cpu != "" {
options = append(options, agent_yaml.WithCPU(cpu))
}
if memory != "" {
options = append(options, agent_yaml.WithMemory(memory))
}
request, err := agent_yaml.CreateAgentAPIRequestFromDefinition(agentDef, options...)
if err != nil {
return nil, exterrors.Validation(
exterrors.CodeInvalidAgentRequest,
fmt.Sprintf("failed to create agent request from definition: %s", err),
"verify the agent.yaml definition is correct",
)
}
// Check enableHostedAgentVNext from azd env first, then OS env
applyVnextMetadata(request, azdEnv)
// Display agent information
p.displayAgentInfo(request)
vnextEnabled := isVnextEnabled(azdEnv)
if vnextEnabled {
// VNext (ADC) flow: auto-provisioning via version status polling
return p.deployHostedAgentVNext(ctx, serviceConfig, progress, request, azdEnv)
}
// Legacy flow: explicit container start/stop
return p.deployHostedAgentLegacy(ctx, serviceConfig, foundryAgentConfig, progress, request, azdEnv)
}
// deployHostedAgentVNext handles VNext (ADC) deployment where provisioning is automatic.
// Creates the agent or a new version, then polls the version status until active.
func (p *AgentServiceTargetProvider) deployHostedAgentVNext(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
progress azdext.ProgressReporter,
request *agent_api.CreateAgentRequest,
azdEnv map[string]string,
) (*azdext.ServiceDeployResult, error) {
const apiVersion = "2025-11-15-preview"
agentClient := agent_api.NewAgentClient(
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
p.credential,
)
// Check if agent already exists (tolerate 404)
progress("Checking if agent exists")
existing, err := agentClient.GetAgent(ctx, request.Name, apiVersion)
var agentVersionResponse *agent_api.AgentVersionObject
if err != nil {
// Check if this is a 404 (agent not found)
var respErr *azcore.ResponseError
if errors.As(err, &respErr) && respErr.StatusCode == 404 {
// Agent does not exist — create it (POST /agents)
progress("Creating agent")
fmt.Fprintf(os.Stderr, "Agent '%s' does not exist, creating...\n", request.Name)
agentObj, createErr := agentClient.CreateAgent(ctx, request, apiVersion)
if createErr != nil {
return nil, exterrors.ServiceFromAzure(createErr, exterrors.OpCreateAgent)
}
agentVersionResponse = &agentObj.Versions.Latest
fmt.Fprintf(os.Stderr, "Agent '%s' created (version %s)\n", agentObj.Name, agentVersionResponse.Version)
} else {
return nil, exterrors.ServiceFromAzure(err, "check-agent-exists")
}
} else {
// Agent exists — create a new version (POST /agents/{name}/versions)
prevVersion := existing.Versions.Latest.Version
fmt.Fprintf(os.Stderr, "Agent '%s' exists (version %s), deploying new version...\n", request.Name, prevVersion)
progress("Creating new agent version")
versionRequest := &agent_api.CreateAgentVersionRequest{
Description: request.Description,
Metadata: request.Metadata,
Definition: request.Definition,
}
agentVersionResponse, err = agentClient.CreateAgentVersion(ctx, request.Name, versionRequest, apiVersion)
if err != nil {
return nil, exterrors.ServiceFromAzure(err, exterrors.OpCreateAgent)
}
fmt.Fprintf(os.Stderr, "Agent version '%s' (version %s) created\n",
agentVersionResponse.Name, agentVersionResponse.Version)
}
// Wait for the version to become active (VNext auto-provisions)
progress("Waiting for agent to become active")
err = p.waitForAgentVersionActive(ctx, agentClient, agentVersionResponse.Name, agentVersionResponse.Version, apiVersion)
if err != nil {
return nil, err
}
// Register agent info in environment
progress("Registering agent environment variables")
err = p.registerAgentEnvironmentVariables(ctx, azdEnv, serviceConfig, agentVersionResponse)
if err != nil {
return nil, err
}
artifacts := p.deployArtifacts(
agentVersionResponse.Name,
agentVersionResponse.Version,
azdEnv["AZURE_AI_PROJECT_ID"],
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
)
return &azdext.ServiceDeployResult{
Artifacts: artifacts,
}, nil
}
// deployHostedAgentLegacy handles the legacy deployment flow with explicit container start/stop.
func (p *AgentServiceTargetProvider) deployHostedAgentLegacy(
ctx context.Context,
serviceConfig *azdext.ServiceConfig,
foundryAgentConfig *ServiceTargetAgentConfig,
progress azdext.ProgressReporter,
request *agent_api.CreateAgentRequest,
azdEnv map[string]string,
) (*azdext.ServiceDeployResult, error) {
// Step 4: Create agent
progress("Creating agent")
agentVersionResponse, err := p.createAgent(ctx, request, azdEnv)
if err != nil {
return nil, err
}
// Step 5: Start agent container
progress("Starting agent container")
err = p.startAgentContainer(ctx, foundryAgentConfig, agentVersionResponse, azdEnv)
if err != nil {
return nil, err
}
// Register agent info in environment
progress("Registering agent environment variables")
err = p.registerAgentEnvironmentVariables(ctx, azdEnv, serviceConfig, agentVersionResponse)
if err != nil {
return nil, err
}
artifacts := p.deployArtifacts(
agentVersionResponse.Name,
agentVersionResponse.Version,
azdEnv["AZURE_AI_PROJECT_ID"],
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
)
return &azdext.ServiceDeployResult{
Artifacts: artifacts,
}, nil
}
// deployArtifacts constructs the artifacts list for deployment results
func (p *AgentServiceTargetProvider) deployArtifacts(
agentName string,
agentVersion string,
projectResourceID string,
projectEndpoint string,
) []*azdext.Artifact {
artifacts := []*azdext.Artifact{}
// Add playground URL
if projectResourceID != "" {
playgroundUrl, err := p.agentPlaygroundUrl(projectResourceID, agentName, agentVersion)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate agent playground link")
} else if playgroundUrl != "" {
artifacts = append(artifacts, &azdext.Artifact{
Kind: azdext.ArtifactKind_ARTIFACT_KIND_ENDPOINT,
Location: playgroundUrl,
LocationKind: azdext.LocationKind_LOCATION_KIND_REMOTE,
Metadata: map[string]string{
"label": "Agent playground (portal)",
},
})
}
}
// Add agent endpoint
if projectEndpoint != "" {
agentEndpoint := p.agentEndpoint(projectEndpoint, agentName, agentVersion)
artifacts = append(artifacts, &azdext.Artifact{
Kind: azdext.ArtifactKind_ARTIFACT_KIND_ENDPOINT,
Location: agentEndpoint,
LocationKind: azdext.LocationKind_LOCATION_KIND_REMOTE,
Metadata: map[string]string{
"agentName": agentName,
"agentVersion": agentVersion,
"label": "Agent endpoint",
"clickable": "false",
"note": "For information on invoking the agent, see " + output.WithLinkFormat(
"https://aka.ms/azd-agents-invoke"),
},
})
}
return artifacts
}
// agentEndpoint constructs the agent endpoint URL from the provided parameters
func (p *AgentServiceTargetProvider) agentEndpoint(projectEndpoint, agentName, agentVersion string) string {
return fmt.Sprintf("%s/agents/%s/versions/%s", projectEndpoint, agentName, agentVersion)
}
// agentPlaygroundUrl constructs a URL to the agent playground in the Foundry portal
func (p *AgentServiceTargetProvider) agentPlaygroundUrl(projectResourceId, agentName, agentVersion string) (string, error) {
resourceId, err := arm.ParseResourceID(projectResourceId)
if err != nil {
return "", err
}
// Encode subscription ID as base64 without padding for URL
subscriptionId := resourceId.SubscriptionID
encodedSubscriptionId, err := encodeSubscriptionID(subscriptionId)
if err != nil {
return "", fmt.Errorf("failed to encode subscription ID: %w", err)
}
resourceGroup := resourceId.ResourceGroupName
if resourceId.Parent == nil {
return "", fmt.Errorf("invalid Microsoft Foundry project ID: %s", projectResourceId)
}
accountName := resourceId.Parent.Name
projectName := resourceId.Name
url := fmt.Sprintf(
"https://ai.azure.com/nextgen/r/%s,%s,,%s,%s/build/agents/%s/build?version=%s",
encodedSubscriptionId, resourceGroup, accountName, projectName, agentName, agentVersion)
return url, nil
}
// createAgent creates a new version of the agent using the API
func (p *AgentServiceTargetProvider) createAgent(
ctx context.Context,
request *agent_api.CreateAgentRequest,
azdEnv map[string]string,
) (*agent_api.AgentVersionObject, error) {
// Create agent client
agentClient := agent_api.NewAgentClient(
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
p.credential,
)
// Use constant API version
const apiVersion = "2025-05-15-preview"
// Extract CreateAgentVersionRequest from CreateAgentRequest
versionRequest := &agent_api.CreateAgentVersionRequest{
Description: request.Description,
Metadata: request.Metadata,
Definition: request.Definition,
}
// Create agent version
agentVersionResponse, err := agentClient.CreateAgentVersion(ctx, request.Name, versionRequest, apiVersion)
if err != nil {
return nil, exterrors.ServiceFromAzure(err, exterrors.OpCreateAgent)
}
fmt.Fprintf(os.Stderr, "Agent version '%s' created successfully!\n", agentVersionResponse.Name)
return agentVersionResponse, nil
}
// startAgentContainer starts the hosted agent container
func (p *AgentServiceTargetProvider) startAgentContainer(
ctx context.Context,
foundryAgentConfig *ServiceTargetAgentConfig,
agentVersionResponse *agent_api.AgentVersionObject,
azdEnv map[string]string,
) error {
fmt.Fprintln(os.Stderr, "Starting Agent Container")
fmt.Fprintln(os.Stderr, "=======================")
// Use constants for wait configuration
const waitForReady = true
const maxWaitTime = 10 * time.Minute
const apiVersion = "2025-05-15-preview"
fmt.Fprintf(os.Stderr, "Using endpoint: %s\n", azdEnv["AZURE_AI_PROJECT_ENDPOINT"])
fmt.Fprintf(os.Stderr, "Agent Name: %s\n", agentVersionResponse.Name)
fmt.Fprintf(os.Stderr, "Agent Version: %s\n", agentVersionResponse.Version)
fmt.Fprintf(os.Stderr, "Wait for Ready: %t\n", waitForReady)
if waitForReady {
fmt.Fprintf(os.Stderr, "Max Wait Time: %v\n", maxWaitTime)
}
fmt.Fprintln(os.Stderr)
// Create agent client
agentClient := agent_api.NewAgentClient(
azdEnv["AZURE_AI_PROJECT_ENDPOINT"],
p.credential,
)
var minReplicas, maxReplicas *int32
if foundryAgentConfig.Container != nil && foundryAgentConfig.Container.Scale != nil {
if foundryAgentConfig.Container.Scale.MinReplicas > 0 {
if foundryAgentConfig.Container.Scale.MinReplicas > math.MaxInt32 {
return exterrors.Validation(
exterrors.CodeInvalidServiceConfig,
fmt.Sprintf("minReplicas exceeds int32 range: %d", foundryAgentConfig.Container.Scale.MinReplicas),
fmt.Sprintf("set container.scale.minReplicas to a value <= %d", math.MaxInt32),
)
}
minReplicasInt32 := int32(foundryAgentConfig.Container.Scale.MinReplicas)
minReplicas = &minReplicasInt32
}
if foundryAgentConfig.Container.Scale.MaxReplicas > 0 {
if foundryAgentConfig.Container.Scale.MaxReplicas > math.MaxInt32 {
return exterrors.Validation(
exterrors.CodeInvalidServiceConfig,
fmt.Sprintf("maxReplicas exceeds int32 range: %d", foundryAgentConfig.Container.Scale.MaxReplicas),
fmt.Sprintf("set container.scale.maxReplicas to a value <= %d", math.MaxInt32),
)
}
maxReplicasInt32 := int32(foundryAgentConfig.Container.Scale.MaxReplicas)
maxReplicas = &maxReplicasInt32
}
}
// Build StartAgentContainerOptions
options := &agent_api.StartAgentContainerOptions{
MinReplicas: minReplicas,
MaxReplicas: maxReplicas,
}
// Start agent container
operation, err := agentClient.StartAgentContainer(
ctx, agentVersionResponse.Name, agentVersionResponse.Version, options, apiVersion)
if err != nil {