From 4f42bb6b06191f691599c363c34cb1bf3803b92c Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Wed, 19 Aug 2026 14:33:40 +0800 Subject: [PATCH 01/14] feat(agents): add unified voice api mode --- cli/azd/extensions/azure.ai.agents/README.md | 28 +++++ .../internal/pkg/agents/agent_api/models.go | 29 +++++ .../pkg/agents/agent_api/operations.go | 87 ++++++++----- .../pkg/agents/agent_api/operations_test.go | 44 +++++++ .../internal/pkg/agents/agent_yaml/map.go | 70 ++++++++++- .../pkg/agents/agent_yaml/map_voice_test.go | 50 ++++++++ .../internal/project/service_target_agent.go | 114 +++++++++++++++--- .../project/service_target_agent_test.go | 38 ++++++ 8 files changed, 412 insertions(+), 48 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/README.md b/cli/azd/extensions/azure.ai.agents/README.md index 80df72db3ac..5425af096d5 100644 --- a/cli/azd/extensions/azure.ai.agents/README.md +++ b/cli/azd/extensions/azure.ai.agents/README.md @@ -133,6 +133,34 @@ Details: > the other inline agent properties such as `codeConfiguration` and > `environmentVariables`. +## Prompt voice agent API mode + +Prompt voice agents (`kind: prompt-voice`) use the legacy `/voice_agents` API by +default while the unified `/agents` voice API rolls out across regions. To run +regression tests against the unified API, set `AZURE_VOICE_AGENT_API` before +`azd deploy`: + +```bash +# Default: legacy /voice_agents API +azd env set AZURE_VOICE_AGENT_API legacy + +# Unified /agents API using the current object-shaped audio.output.voice payload +azd env set AZURE_VOICE_AGENT_API unified + +# Unified /agents API using the TiP/spec flat audio.output.voice payload +azd env set AZURE_VOICE_AGENT_API unified-flat +``` + +Details: + +- `legacy` remains the default and preserves existing behavior. +- `unified` and `unified-flat` create voice agents through `/agents`; repeat + deploys update the existing agent and create a new version through + `/agents/{name}` when the agent name is already present in the azd environment. +- `unified-flat` is intended for TiP/new-service validation. Non-TiP regions may + still require `legacy` or `unified` until the flat output shape is fully + rolled out. + ## Session idle timeout A hosted agent's runtime session sandbox is suspended by Foundry after a period diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go index a276ef6559c..96b33806e95 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go @@ -350,12 +350,28 @@ type VoiceOutputConfig struct { Voice *VoiceConfig `json:"voice,omitempty"` } +// VoiceOutputConfigFlat is the newer Voice Live output shape used by the +// unified /agents voice API in TiP. Older regions still accept/return the +// object-shaped VoiceOutputConfig above. +type VoiceOutputConfigFlat struct { + Format *VoiceAudioFormat `json:"format,omitempty"` + Voice string `json:"voice,omitempty"` + VoiceType string `json:"voice_type,omitempty"` + VoiceLocale string `json:"voice_locale,omitempty"` +} + // VoiceAudioConfig bundles the input and output audio configuration. type VoiceAudioConfig struct { Input *VoiceInputConfig `json:"input,omitempty"` Output *VoiceOutputConfig `json:"output,omitempty"` } +// VoiceAudioConfigFlat bundles voice audio config with the flat output shape. +type VoiceAudioConfigFlat struct { + Input *VoiceInputConfig `json:"input,omitempty"` + Output *VoiceOutputConfigFlat `json:"output,omitempty"` +} + // VoiceAgentDefinition is the data-plane definition body POSTed to the // /voice_agents collection for a declarative (managed) voice agent. Its Kind // is always AgentKindVoice ("voice"). @@ -369,6 +385,19 @@ type VoiceAgentDefinition struct { Store *bool `json:"store,omitempty"` } +// VoiceAgentDefinitionFlat is the voice definition shape aligned with the +// unified /agents TiP API, where audio.output.voice is a string and the voice +// provider details are sibling fields. +type VoiceAgentDefinitionFlat struct { + AgentDefinition + ModelType VoiceModelType `json:"model_type"` + Model string `json:"model"` + Instructions string `json:"instructions,omitempty"` + Audio *VoiceAudioConfigFlat `json:"audio,omitempty"` + OutputModalities []string `json:"output_modalities,omitempty"` + Store *bool `json:"store,omitempty"` +} + // CreateAgentVersionRequest represents a request to create an agent version type CreateAgentVersionRequest struct { Description *string `json:"description,omitempty"` diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go index c94ebc69294..46c0d9d5e44 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go @@ -167,47 +167,24 @@ func (c *AgentClient) CreateAgent(ctx context.Context, request *CreateAgentReque // header while voice agents remain a preview capability. const voiceAgentsPreviewFeature = "VoiceAgents=V1Preview" -// CreateVoiceAgent creates a new declarative (managed) voice agent. -// -// Voice agents live in a separate data-plane collection (/voice_agents), distinct -// from the /agents collection used by hosted/workflow agents. The request -// Definition must be a *VoiceAgentDefinition (service kind "voice"). -// -// overriddenHost, when non-empty, is sent as the x-ms-overridden-host header. -// This routes the request directly to the regional Hyena data-plane host, -// bypassing the public Foundry APIM (whose voice route may not yet be rolled -// out). Pass "" to use the default endpoint routing. -// -// Redeploy semantics: the voice data-plane exposes create-only POST /voice_agents -// with no version/upsert model (unlike hosted agents, which mint a new -// agent-version per deploy). A second `azd deploy` of the same voice service -// therefore re-POSTs with the same name and the service rejects it with a -// non-success status, which this method surfaces as a deploy error rather than -// silently overwriting the existing agent. Idempotent redeploy/update is tracked -// as a follow-up (see the PR "Follow-ups" section); until the service adds an -// update route, redeploy requires deleting the existing voice agent first. -func (c *AgentClient) CreateVoiceAgent( +func (c *AgentClient) doVoiceJSONAgentRequest( ctx context.Context, - request *CreateAgentRequest, - apiVersion string, + method string, + url string, + request any, overriddenHost string, ) (*AgentObject, error) { - url := fmt.Sprintf("%s/voice_agents?api-version=%s", c.endpoint, apiVersion) - payload, err := json.Marshal(request) if err != nil { return nil, fmt.Errorf("failed to marshal request: %w", err) } - req, err := runtime.NewRequest(ctx, http.MethodPost, url) + req, err := runtime.NewRequest(ctx, method, url) if err != nil { return nil, fmt.Errorf("failed to create request: %w", err) } - // Voice agents are a preview feature; the service rejects the request with - // 403 preview_feature_required unless this opt-in header is present. req.Raw().Header.Set("Foundry-Features", voiceAgentsPreviewFeature) - if overriddenHost != "" { req.Raw().Header.Set("x-ms-overridden-host", overriddenHost) } @@ -239,6 +216,60 @@ func (c *AgentClient) CreateVoiceAgent( return &agent, nil } +// CreateVoiceAgent creates a new declarative (managed) voice agent. +// +// Voice agents live in a separate data-plane collection (/voice_agents), distinct +// from the /agents collection used by hosted/workflow agents. The request +// Definition must be a *VoiceAgentDefinition (service kind "voice"). +// +// overriddenHost, when non-empty, is sent as the x-ms-overridden-host header. +// This routes the request directly to the regional Hyena data-plane host, +// bypassing the public Foundry APIM (whose voice route may not yet be rolled +// out). Pass "" to use the default endpoint routing. +// +// Redeploy semantics: the voice data-plane exposes create-only POST /voice_agents +// with no version/upsert model (unlike hosted agents, which mint a new +// agent-version per deploy). A second `azd deploy` of the same voice service +// therefore re-POSTs with the same name and the service rejects it with a +// non-success status, which this method surfaces as a deploy error rather than +// silently overwriting the existing agent. Idempotent redeploy/update is tracked +// as a follow-up (see the PR "Follow-ups" section); until the service adds an +// update route, redeploy requires deleting the existing voice agent first. +func (c *AgentClient) CreateVoiceAgent( + ctx context.Context, + request *CreateAgentRequest, + apiVersion string, + overriddenHost string, +) (*AgentObject, error) { + url := fmt.Sprintf("%s/voice_agents?api-version=%s", c.endpoint, apiVersion) + return c.doVoiceJSONAgentRequest(ctx, http.MethodPost, url, request, overriddenHost) +} + +// CreateVoiceAgentUnified creates a voice agent through the unified /agents +// collection. This path is opt-in while regional rollout is still in progress. +func (c *AgentClient) CreateVoiceAgentUnified( + ctx context.Context, + request *CreateAgentRequest, + apiVersion string, + overriddenHost string, +) (*AgentObject, error) { + url := fmt.Sprintf("%s/agents?api-version=%s", c.endpoint, apiVersion) + return c.doVoiceJSONAgentRequest(ctx, http.MethodPost, url, request, overriddenHost) +} + +// UpdateVoiceAgentUnified creates a new version for an existing voice agent +// through the unified /agents/{name} endpoint. +func (c *AgentClient) UpdateVoiceAgentUnified( + ctx context.Context, + agentName string, + request *UpdateAgentRequest, + apiVersion string, + overriddenHost string, +) (*AgentObject, error) { + url := fmt.Sprintf("%s/agents/%s?api-version=%s", c.endpoint, agentName, apiVersion) + return c.doVoiceJSONAgentRequest(ctx, http.MethodPost, url, request, overriddenHost) +} + // UpdateAgent updates an existing agent func (c *AgentClient) UpdateAgent(ctx context.Context, agentName string, request *UpdateAgentRequest, apiVersion string) (*AgentObject, error) { url := fmt.Sprintf("%s/agents/%s?api-version=%s", c.endpoint, agentName, apiVersion) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go index 6eb2effae43..cf4d9a116b3 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go @@ -948,6 +948,50 @@ func TestCreateVoiceAgent_PostsToVoiceCollectionWithPreviewHeader(t *testing.T) require.Contains(t, string(reqBody), `"name":"my-voice"`) } +func TestCreateVoiceAgentUnified_PostsToAgentsWithPreviewHeader(t *testing.T) { + body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{}}}` + client, transport := newCaptureClient(http.StatusOK, body) + + agent, err := client.CreateVoiceAgentUnified( + t.Context(), + &CreateAgentRequest{Name: "my-voice"}, + AgentEndpointAPIVersion, + "", + ) + + require.NoError(t, err) + require.Equal(t, "my-voice", agent.Name) + require.Len(t, transport.requests, 1) + req := transport.requests[0] + require.Equal(t, http.MethodPost, req.Method) + require.Equal(t, "/api/projects/proj/agents", req.URL.Path) + require.Equal(t, AgentEndpointAPIVersion, req.URL.Query().Get("api-version")) + require.Equal(t, voiceAgentsPreviewFeature, req.Header.Get("Foundry-Features")) +} + +func TestUpdateVoiceAgentUnified_PostsToNamedAgentWithPreviewHeader(t *testing.T) { + body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{"version":"2"}}}` + client, transport := newCaptureClient(http.StatusOK, body) + + agent, err := client.UpdateVoiceAgentUnified( + t.Context(), + "my-voice", + &UpdateAgentRequest{}, + AgentEndpointAPIVersion, + "regional.hyena.example.com", + ) + + require.NoError(t, err) + require.Equal(t, "my-voice", agent.Name) + require.Len(t, transport.requests, 1) + req := transport.requests[0] + require.Equal(t, http.MethodPost, req.Method) + require.Equal(t, "/api/projects/proj/agents/my-voice", req.URL.Path) + require.Equal(t, AgentEndpointAPIVersion, req.URL.Query().Get("api-version")) + require.Equal(t, voiceAgentsPreviewFeature, req.Header.Get("Foundry-Features")) + require.Equal(t, "regional.hyena.example.com", req.Header.Get("x-ms-overridden-host")) +} + func TestCreateVoiceAgent_SetsOverriddenHostHeader(t *testing.T) { client, transport := newCaptureClient(http.StatusCreated, `{"name":"my-voice","versions":{"latest":{}}}`) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go index 8a385d27632..0404762cb43 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go @@ -553,10 +553,41 @@ func buildVoiceConfig(name string) *agent_api.VoiceConfig { return &agent_api.VoiceConfig{Type: "azure_standard", Name: trimmed} } +func flatVoiceType(voice *agent_api.VoiceConfig) string { + if voice == nil { + return "" + } + if voice.Type == "azure_standard" { + return "azure-standard" + } + return voice.Type +} + +func flatVoiceLocale(voice *agent_api.VoiceConfig) string { + if voice == nil || voice.Name == "" || isOpenAIVoice(voice.Name) { + return "" + } + parts := strings.SplitN(voice.Name, "-", 3) + if len(parts) < 2 { + return "" + } + return parts[0] + "-" + parts[1] +} + // CreateVoiceAgentAPIRequest builds a CreateAgentRequest for a declarative // voice agent. It translates the authoring kind "prompt-voice" into the // data-plane service kind "voice" and defaults the audio pipeline. func CreateVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { + return createVoiceAgentAPIRequest(voiceAgent, false) +} + +// CreateVoiceAgentAPIRequestFlat builds a CreateAgentRequest using the newer +// TiP/unified API flat output voice shape. +func CreateVoiceAgentAPIRequestFlat(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { + return createVoiceAgentAPIRequest(voiceAgent, true) +} + +func createVoiceAgentAPIRequest(voiceAgent VoiceAgent, flatOutput bool) (*agent_api.CreateAgentRequest, error) { modelID := "" if voiceAgent.Model != nil { modelID = strings.TrimSpace(voiceAgent.Model.Id) @@ -590,6 +621,37 @@ func CreateVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRe Rate: defaultVoiceAudioRate, } + input := &agent_api.VoiceInputConfig{ + Format: audioFormat, + TurnDetection: &agent_api.VoiceTurnDetection{Type: defaultVoiceTurnDetectionType}, + Transcription: &agent_api.VoiceTranscription{Model: defaultVoiceInputTranscriptionModel}, + } + voiceConfig := buildVoiceConfig(voiceName) + if flatOutput { + voiceDef := agent_api.VoiceAgentDefinitionFlat{ + AgentDefinition: agent_api.AgentDefinition{ + // Translate authoring kind prompt-voice -> service kind voice. + Kind: agent_api.AgentKindVoice, + }, + ModelType: modelType, + Model: modelID, + Instructions: instructions, + Audio: &agent_api.VoiceAudioConfigFlat{ + Input: input, + Output: &agent_api.VoiceOutputConfigFlat{ + Format: audioFormat, + Voice: voiceConfig.Name, + VoiceType: flatVoiceType(voiceConfig), + VoiceLocale: flatVoiceLocale(voiceConfig), + }, + }, + OutputModalities: []string{"audio"}, + Store: voiceAgent.Store, + } + + return createAgentAPIRequest(voiceAgent.AgentDefinition, voiceDef, nil, nil) + } + voiceDef := agent_api.VoiceAgentDefinition{ AgentDefinition: agent_api.AgentDefinition{ // Translate authoring kind prompt-voice -> service kind voice. @@ -599,14 +661,10 @@ func CreateVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRe Model: modelID, Instructions: instructions, Audio: &agent_api.VoiceAudioConfig{ - Input: &agent_api.VoiceInputConfig{ - Format: audioFormat, - TurnDetection: &agent_api.VoiceTurnDetection{Type: defaultVoiceTurnDetectionType}, - Transcription: &agent_api.VoiceTranscription{Model: defaultVoiceInputTranscriptionModel}, - }, + Input: input, Output: &agent_api.VoiceOutputConfig{ Format: audioFormat, - Voice: buildVoiceConfig(voiceName), + Voice: voiceConfig, }, }, OutputModalities: []string{"audio"}, diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go index 137e9b6e847..2ce594e1fbf 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go @@ -172,6 +172,56 @@ func TestCreateVoiceAgentAPIRequest_Overrides(t *testing.T) { } } +func TestCreateVoiceAgentAPIRequestFlat_UsesFlatOutputShape(t *testing.T) { + t.Parallel() + voice := "alloy" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-flat"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &voice, + } + + req, err := CreateVoiceAgentAPIRequestFlat(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + def := req.Definition.(agent_api.VoiceAgentDefinitionFlat) + if def.Audio.Output.Voice != "alloy" { + t.Errorf("Voice = %q, want alloy", def.Audio.Output.Voice) + } + if def.Audio.Output.VoiceType != "openai" { + t.Errorf("VoiceType = %q, want openai", def.Audio.Output.VoiceType) + } + if def.Audio.Output.VoiceLocale != "" { + t.Errorf("VoiceLocale = %q, want empty", def.Audio.Output.VoiceLocale) + } +} + +func TestCreateVoiceAgentAPIRequestFlat_AzureVoiceLocale(t *testing.T) { + t.Parallel() + voice := "en-US-Ava:DragonHDLatestNeural" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-flat"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &voice, + } + + req, err := CreateVoiceAgentAPIRequestFlat(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + def := req.Definition.(agent_api.VoiceAgentDefinitionFlat) + if def.Audio.Output.Voice != voice { + t.Errorf("Voice = %q, want %q", def.Audio.Output.Voice, voice) + } + if def.Audio.Output.VoiceType != "azure-standard" { + t.Errorf("VoiceType = %q, want azure-standard", def.Audio.Output.VoiceType) + } + if def.Audio.Output.VoiceLocale != "en-US" { + t.Errorf("VoiceLocale = %q, want en-US", def.Audio.Output.VoiceLocale) + } +} + // TestCreateVoiceAgentAPIRequest_ExplicitManaged verifies that explicitly // setting model_type: managed is accepted (idempotent with the default). func TestCreateVoiceAgentAPIRequest_ExplicitManaged(t *testing.T) { diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 3f4039392a2..676b1ecfcbe 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -2151,12 +2151,50 @@ func (p *AgentServiceTargetProvider) deployHostedAgent( //nolint:gosec // env var key name, not a credential const voiceOverriddenHostEnvKey = "AZURE_VOICE_OVERRIDDEN_HOST" +// voiceAgentAPIEnvKey controls which voice deployment API azd uses. It defaults +// to the legacy /voice_agents path while the unified API rolls out regionally. +// Supported values: +// - legacy: POST /voice_agents with object-shaped audio.output.voice +// - unified: POST /agents or /agents/{name} with object-shaped audio.output.voice +// - unified-flat: POST /agents or /agents/{name} with flat audio.output.voice +// +//nolint:gosec // env var key name, not a credential +const voiceAgentAPIEnvKey = "AZURE_VOICE_AGENT_API" + +type voiceAgentAPIMode string + +const ( + voiceAgentAPIModeLegacy voiceAgentAPIMode = "legacy" + voiceAgentAPIModeUnified voiceAgentAPIMode = "unified" + voiceAgentAPIModeUnifiedFlat voiceAgentAPIMode = "unified-flat" +) + +func resolveVoiceAgentAPIMode(azdEnv map[string]string) (voiceAgentAPIMode, error) { + mode := strings.TrimSpace(azdEnv[voiceAgentAPIEnvKey]) + if mode == "" { + mode = strings.TrimSpace(os.Getenv(voiceAgentAPIEnvKey)) + } + mode = strings.ToLower(strings.ReplaceAll(mode, "_", "-")) + if mode == "" { + return voiceAgentAPIModeLegacy, nil + } + switch voiceAgentAPIMode(mode) { + case voiceAgentAPIModeLegacy, voiceAgentAPIModeUnified, voiceAgentAPIModeUnifiedFlat: + return voiceAgentAPIMode(mode), nil + default: + return "", fmt.Errorf( + "%s must be one of %q, %q, or %q", + voiceAgentAPIEnvKey, voiceAgentAPIModeLegacy, voiceAgentAPIModeUnified, voiceAgentAPIModeUnifiedFlat, + ) + } +} + // deployVoiceAgent deploys a declarative (managed) voice agent (kind: -// prompt-voice) to the Foundry service. Unlike hosted agents, voice agents are -// created synchronously via a single POST to /voice_agents that returns the -// created AgentObject directly — there is no container build, no agent-version -// object, and no active-state polling. This method is intentionally isolated -// from the container deploy path so the two contracts never entangle. +// prompt-voice) to the Foundry service. The legacy /voice_agents API remains +// the default while unified /agents rolls out regionally; AZURE_VOICE_AGENT_API +// can opt into unified modes for regression and TiP validation. This method is +// intentionally isolated from the container deploy path so the two contracts +// never entangle. func (p *AgentServiceTargetProvider) deployVoiceAgent( ctx context.Context, serviceConfig *azdext.ServiceConfig, @@ -2166,7 +2204,21 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( ) (*azdext.ServiceDeployResult, error) { progress("Deploying voice agent") - request, err := agent_yaml.CreateVoiceAgentAPIRequest(va) + apiMode, err := resolveVoiceAgentAPIMode(azdEnv) + if err != nil { + return nil, exterrors.Validation( + exterrors.CodeInvalidAgentManifest, + err.Error(), + fmt.Sprintf("set %s to legacy, unified, or unified-flat", voiceAgentAPIEnvKey), + ) + } + + var request *agent_api.CreateAgentRequest + if apiMode == voiceAgentAPIModeUnifiedFlat { + request, err = agent_yaml.CreateVoiceAgentAPIRequestFlat(va) + } else { + request, err = agent_yaml.CreateVoiceAgentAPIRequest(va) + } if err != nil { return nil, exterrors.Validation( exterrors.CodeInvalidAgentManifest, @@ -2187,22 +2239,19 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( agentClient := agent_api.NewAgentClient(projectEndpoint, p.credential) - progress("Creating voice agent") - agentObject, err := agentClient.CreateVoiceAgent( - ctx, request, agent_api.AgentEndpointAPIVersion, azdEnv[voiceOverriddenHostEnvKey], + serviceKey := p.getServiceKey(serviceConfig.Name) + agentObject, err := p.deployVoiceAgentWithMode( + ctx, agentClient, request, apiMode, serviceKey, azdEnv, progress, ) if err != nil { return nil, exterrors.ServiceFromAzure(err, exterrors.OpCreateAgent) } - fmt.Fprintf(os.Stderr, "Voice agent '%s' created successfully!\n", agentObject.Name) + fmt.Fprintf(os.Stderr, "Voice agent '%s' deployed successfully!\n", agentObject.Name) // Persist NAME first and ENDPOINT last. ENDPOINT is used as the voice deploy // completion marker by other commands, so avoid writing it before NAME. - serviceKey := p.getServiceKey(serviceConfig.Name) - baseEndpoint := fmt.Sprintf( - "%s/voice_agents/%s", strings.TrimRight(projectEndpoint, "/"), agentObject.Name, - ) + baseEndpoint := voiceAgentEndpoint(projectEndpoint, agentObject.Name, apiMode) for _, envVar := range []struct{ key, value string }{ {fmt.Sprintf("AGENT_%s_NAME", serviceKey), agentObject.Name}, {fmt.Sprintf("AGENT_%s_ENDPOINT", serviceKey), baseEndpoint}, @@ -2230,6 +2279,43 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( return &azdext.ServiceDeployResult{Artifacts: artifacts}, nil } +func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( + ctx context.Context, + agentClient *agent_api.AgentClient, + request *agent_api.CreateAgentRequest, + apiMode voiceAgentAPIMode, + serviceKey string, + azdEnv map[string]string, + progress azdext.ProgressReporter, +) (*agent_api.AgentObject, error) { + overriddenHost := azdEnv[voiceOverriddenHostEnvKey] + if apiMode == voiceAgentAPIModeLegacy { + progress("Creating voice agent using legacy API") + return agentClient.CreateVoiceAgent(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) + } + + if existingName := strings.TrimSpace(azdEnv[fmt.Sprintf("AGENT_%s_NAME", serviceKey)]); existingName != "" { + progress("Updating voice agent using unified API") + updateRequest := &agent_api.UpdateAgentRequest{ + CreateAgentVersionRequest: request.CreateAgentVersionRequest, + } + return agentClient.UpdateVoiceAgentUnified( + ctx, existingName, updateRequest, agent_api.AgentEndpointAPIVersion, overriddenHost, + ) + } + + progress("Creating voice agent using unified API") + return agentClient.CreateVoiceAgentUnified(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) +} + +func voiceAgentEndpoint(projectEndpoint string, agentName string, apiMode voiceAgentAPIMode) string { + trimmedEndpoint := strings.TrimRight(projectEndpoint, "/") + if apiMode == voiceAgentAPIModeLegacy { + return fmt.Sprintf("%s/voice_agents/%s", trimmedEndpoint, agentName) + } + return fmt.Sprintf("%s/agents/%s/endpoint/protocols/voice", trimmedEndpoint, agentName) +} + // packageCodeDeploy creates a ZIP archive of the agent source code, writes it to a temp file, // and computes its SHA-256. Returns the temp file path and SHA-256 hex string. func (p *AgentServiceTargetProvider) packageCodeDeploy(ctx context.Context, serviceConfig *azdext.ServiceConfig) (string, string, error) { diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go index 9e48effc3c0..4f2f230dafc 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go @@ -668,6 +668,44 @@ func TestAdoptServiceConfigIgnoresNilAndKeepsResolvedState(t *testing.T) { require.False(t, provider.serviceConfigResolved) } +func TestResolveVoiceAgentAPIMode_DefaultsToLegacy(t *testing.T) { + t.Setenv(voiceAgentAPIEnvKey, "") + mode, err := resolveVoiceAgentAPIMode(map[string]string{}) + require.NoError(t, err) + require.Equal(t, voiceAgentAPIModeLegacy, mode) +} + +func TestResolveVoiceAgentAPIMode_EnvValues(t *testing.T) { + t.Setenv(voiceAgentAPIEnvKey, "unified_flat") + mode, err := resolveVoiceAgentAPIMode(map[string]string{}) + require.NoError(t, err) + require.Equal(t, voiceAgentAPIModeUnifiedFlat, mode) + + mode, err = resolveVoiceAgentAPIMode(map[string]string{voiceAgentAPIEnvKey: "unified"}) + require.NoError(t, err) + require.Equal(t, voiceAgentAPIModeUnified, mode) +} + +func TestResolveVoiceAgentAPIMode_Invalid(t *testing.T) { + _, err := resolveVoiceAgentAPIMode(map[string]string{voiceAgentAPIEnvKey: "future"}) + require.Error(t, err) + require.Contains(t, err.Error(), voiceAgentAPIEnvKey) +} + +func TestVoiceAgentEndpoint_ByMode(t *testing.T) { + projectEndpoint := "https://proj.services.ai.azure.com/api/projects/p/" + require.Equal( + t, + "https://proj.services.ai.azure.com/api/projects/p/voice_agents/my-agent", + voiceAgentEndpoint(projectEndpoint, "my-agent", voiceAgentAPIModeLegacy), + ) + require.Equal( + t, + "https://proj.services.ai.azure.com/api/projects/p/agents/my-agent/endpoint/protocols/voice", + voiceAgentEndpoint(projectEndpoint, "my-agent", voiceAgentAPIModeUnified), + ) +} + func createSymlinkOrSkip(t *testing.T, oldname, newname string) { t.Helper() From 27073e789f7ca71f63160c32b6b35cd0501cc915 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Wed, 19 Aug 2026 15:15:42 +0800 Subject: [PATCH 02/14] docs(agents): clarify voice deploy routing comment --- .../internal/project/service_target_agent.go | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 676b1ecfcbe..d240f13545f 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -1376,13 +1376,11 @@ func (p *AgentServiceTargetProvider) Deploy( return nil, err } - // Voice agents (kind: prompt-voice) use a fundamentally different data-plane - // contract than hosted/workflow agents: a synchronous POST to /voice_agents - // that returns an AgentObject directly, with no version/polling model. Resolve - // the definition first — honoring the AGENT_DEFINITION_PATH override precedence - // so an override drives this dispatch just as it does the container path — and - // route voice to an isolated method so the container deploy path below stays - // byte-for-byte unchanged. + // Voice agents (kind: prompt-voice) use a different data-plane contract than + // hosted/workflow agents. Resolve the definition first — honoring the + // AGENT_DEFINITION_PATH override precedence so an override drives this dispatch + // just as it does the container path — and route voice to an isolated method so + // the container deploy path below stays byte-for-byte unchanged. if isVoice { return p.deployVoiceAgent(ctx, serviceConfig, voiceAgent, azdEnv, progress) } From 16e94ae2bac0d9af3b45b84c145612226e42a85f Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 10:39:37 +0800 Subject: [PATCH 03/14] fix(agents): harden unified voice deploy --- cli/azd/extensions/azure.ai.agents/README.md | 9 ++-- .../pkg/agents/agent_api/operations.go | 43 +++++++++++++++ .../pkg/agents/agent_api/operations_test.go | 23 ++++++++ .../internal/project/service_target_agent.go | 52 +++++++++++++++---- .../project/service_target_agent_test.go | 14 ++++- 5 files changed, 126 insertions(+), 15 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/README.md b/cli/azd/extensions/azure.ai.agents/README.md index 5425af096d5..6fecb7e17db 100644 --- a/cli/azd/extensions/azure.ai.agents/README.md +++ b/cli/azd/extensions/azure.ai.agents/README.md @@ -154,9 +154,12 @@ azd env set AZURE_VOICE_AGENT_API unified-flat Details: - `legacy` remains the default and preserves existing behavior. -- `unified` and `unified-flat` create voice agents through `/agents`; repeat - deploys update the existing agent and create a new version through - `/agents/{name}` when the agent name is already present in the azd environment. +- `unified` and `unified-flat` check `/agents/{name}` remotely before deploying: + `404` creates through `/agents`, while `200` updates through `/agents/{name}`. +- Unified modes write `AGENT__VERSION` and store the callable voice + WebSocket endpoint as `wss://.../agents/{name}/endpoint/protocols/voice?api-version=v1`. +- `legacy` clears any stale `AGENT__VERSION` value and preserves the + existing `/voice_agents/{name}` endpoint marker. - `unified-flat` is intended for TiP/new-service validation. Non-TiP regions may still require `legacy` or `unified` until the flat output shape is fully rolled out. diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go index 46c0d9d5e44..fbd6f514ef3 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go @@ -245,6 +245,49 @@ func (c *AgentClient) CreateVoiceAgent( return c.doVoiceJSONAgentRequest(ctx, http.MethodPost, url, request, overriddenHost) } +// GetVoiceAgentUnified retrieves a voice agent through the unified /agents +// endpoint with the voice preview opt-in header. Use this instead of GetAgent +// when deciding whether to create or update a prompt voice agent. +func (c *AgentClient) GetVoiceAgentUnified( + ctx context.Context, + agentName string, + apiVersion string, + overriddenHost string, +) (*AgentObject, error) { + url := fmt.Sprintf("%s/agents/%s?api-version=%s", c.endpoint, agentName, apiVersion) + req, err := runtime.NewRequest(ctx, http.MethodGet, url) + if err != nil { + return nil, fmt.Errorf("failed to create request: %w", err) + } + + req.Raw().Header.Set("Foundry-Features", voiceAgentsPreviewFeature) + if overriddenHost != "" { + req.Raw().Header.Set("x-ms-overridden-host", overriddenHost) + } + + resp, err := c.pipeline.Do(req) + if err != nil { + return nil, fmt.Errorf("HTTP request failed: %w", err) + } + defer resp.Body.Close() + + if !runtime.HasStatusCode(resp, http.StatusOK) { + return nil, runtime.NewResponseError(resp) + } + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + var agent AgentObject + if err := json.Unmarshal(body, &agent); err != nil { + return nil, fmt.Errorf("failed to parse response: %w", err) + } + + return &agent, nil +} + // CreateVoiceAgentUnified creates a voice agent through the unified /agents // collection. This path is opt-in while regional rollout is still in progress. func (c *AgentClient) CreateVoiceAgentUnified( diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go index cf4d9a116b3..7aacd0d7ba5 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go @@ -969,6 +969,29 @@ func TestCreateVoiceAgentUnified_PostsToAgentsWithPreviewHeader(t *testing.T) { require.Equal(t, voiceAgentsPreviewFeature, req.Header.Get("Foundry-Features")) } +func TestGetVoiceAgentUnified_GetsNamedAgentWithPreviewHeader(t *testing.T) { + body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{"version":"3"}}}` + client, transport := newCaptureClient(http.StatusOK, body) + + agent, err := client.GetVoiceAgentUnified( + t.Context(), + "my-voice", + AgentEndpointAPIVersion, + "regional.hyena.example.com", + ) + + require.NoError(t, err) + require.Equal(t, "my-voice", agent.Name) + require.Equal(t, "3", agent.Versions.Latest.Version) + require.Len(t, transport.requests, 1) + req := transport.requests[0] + require.Equal(t, http.MethodGet, req.Method) + require.Equal(t, "/api/projects/proj/agents/my-voice", req.URL.Path) + require.Equal(t, AgentEndpointAPIVersion, req.URL.Query().Get("api-version")) + require.Equal(t, voiceAgentsPreviewFeature, req.Header.Get("Foundry-Features")) + require.Equal(t, "regional.hyena.example.com", req.Header.Get("x-ms-overridden-host")) +} + func TestUpdateVoiceAgentUnified_PostsToNamedAgentWithPreviewHeader(t *testing.T) { body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{"version":"2"}}}` client, transport := newCaptureClient(http.StatusOK, body) diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index d240f13545f..6c0c15c8d15 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -130,6 +130,19 @@ func buildInvocationsWSProtocolURL(projectEndpoint, agentName string) string { ) } +func buildVoiceWSProtocolURL(projectEndpoint, agentName string) string { + projectEndpoint = strings.TrimSpace(projectEndpoint) + u, err := url.Parse(projectEndpoint) + if err != nil || u.Host == "" { + return "" + } + + return fmt.Sprintf( + "wss://%s%s/agents/%s/endpoint/protocols/voice?api-version=%s", + u.Host, strings.TrimRight(u.Path, "/"), agentName, agent_api.AgentEndpointAPIVersion, + ) +} + // ProtocolEnvSuffix pairs a user-facing label with the env var suffix // used in AGENT_{KEY}_{SUFFIX}_ENDPOINT variables. type ProtocolEnvSuffix struct { @@ -2238,11 +2251,11 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( agentClient := agent_api.NewAgentClient(projectEndpoint, p.credential) serviceKey := p.getServiceKey(serviceConfig.Name) - agentObject, err := p.deployVoiceAgentWithMode( - ctx, agentClient, request, apiMode, serviceKey, azdEnv, progress, + agentObject, deployOp, err := p.deployVoiceAgentWithMode( + ctx, agentClient, request, apiMode, azdEnv, progress, ) if err != nil { - return nil, exterrors.ServiceFromAzure(err, exterrors.OpCreateAgent) + return nil, exterrors.ServiceFromAzure(err, deployOp) } fmt.Fprintf(os.Stderr, "Voice agent '%s' deployed successfully!\n", agentObject.Name) @@ -2250,8 +2263,14 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( // Persist NAME first and ENDPOINT last. ENDPOINT is used as the voice deploy // completion marker by other commands, so avoid writing it before NAME. baseEndpoint := voiceAgentEndpoint(projectEndpoint, agentObject.Name, apiMode) + versionKey := fmt.Sprintf("AGENT_%s_VERSION", serviceKey) + versionValue := "" + if apiMode != voiceAgentAPIModeLegacy { + versionValue = agentObject.Versions.Latest.Version + } for _, envVar := range []struct{ key, value string }{ {fmt.Sprintf("AGENT_%s_NAME", serviceKey), agentObject.Name}, + {versionKey, versionValue}, {fmt.Sprintf("AGENT_%s_ENDPOINT", serviceKey), baseEndpoint}, } { if _, setErr := p.azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{ @@ -2282,28 +2301,39 @@ func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( agentClient *agent_api.AgentClient, request *agent_api.CreateAgentRequest, apiMode voiceAgentAPIMode, - serviceKey string, azdEnv map[string]string, progress azdext.ProgressReporter, -) (*agent_api.AgentObject, error) { +) (*agent_api.AgentObject, string, error) { overriddenHost := azdEnv[voiceOverriddenHostEnvKey] if apiMode == voiceAgentAPIModeLegacy { progress("Creating voice agent using legacy API") - return agentClient.CreateVoiceAgent(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) + agentObject, err := agentClient.CreateVoiceAgent(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) + return agentObject, exterrors.OpCreateAgent, err } - if existingName := strings.TrimSpace(azdEnv[fmt.Sprintf("AGENT_%s_NAME", serviceKey)]); existingName != "" { + remoteAgent, getErr := agentClient.GetVoiceAgentUnified( + ctx, request.Name, agent_api.AgentEndpointAPIVersion, overriddenHost, + ) + if getErr == nil && remoteAgent != nil { progress("Updating voice agent using unified API") updateRequest := &agent_api.UpdateAgentRequest{ CreateAgentVersionRequest: request.CreateAgentVersionRequest, } - return agentClient.UpdateVoiceAgentUnified( - ctx, existingName, updateRequest, agent_api.AgentEndpointAPIVersion, overriddenHost, + agentObject, err := agentClient.UpdateVoiceAgentUnified( + ctx, request.Name, updateRequest, agent_api.AgentEndpointAPIVersion, overriddenHost, ) + return agentObject, exterrors.OpUpdateAgent, err + } + if getErr != nil { + var respErr *azcore.ResponseError + if !errors.As(getErr, &respErr) || respErr.StatusCode != http.StatusNotFound { + return nil, exterrors.OpCreateAgent, getErr + } } progress("Creating voice agent using unified API") - return agentClient.CreateVoiceAgentUnified(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) + agentObject, err := agentClient.CreateVoiceAgentUnified(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) + return agentObject, exterrors.OpCreateAgent, err } func voiceAgentEndpoint(projectEndpoint string, agentName string, apiMode voiceAgentAPIMode) string { @@ -2311,7 +2341,7 @@ func voiceAgentEndpoint(projectEndpoint string, agentName string, apiMode voiceA if apiMode == voiceAgentAPIModeLegacy { return fmt.Sprintf("%s/voice_agents/%s", trimmedEndpoint, agentName) } - return fmt.Sprintf("%s/agents/%s/endpoint/protocols/voice", trimmedEndpoint, agentName) + return buildVoiceWSProtocolURL(trimmedEndpoint, agentName) } // packageCodeDeploy creates a ZIP archive of the agent source code, writes it to a temp file, diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go index 4f2f230dafc..c6e339cd615 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go @@ -701,11 +701,23 @@ func TestVoiceAgentEndpoint_ByMode(t *testing.T) { ) require.Equal( t, - "https://proj.services.ai.azure.com/api/projects/p/agents/my-agent/endpoint/protocols/voice", + "wss://proj.services.ai.azure.com/api/projects/p/agents/my-agent/endpoint/protocols/voice?api-version=v1", voiceAgentEndpoint(projectEndpoint, "my-agent", voiceAgentAPIModeUnified), ) } +func TestBuildVoiceWSProtocolURL(t *testing.T) { + got := buildVoiceWSProtocolURL( + "https://acct.services.ai.azure.com/api/projects/proj/", + "voice-agent", + ) + require.Equal( + t, + "wss://acct.services.ai.azure.com/api/projects/proj/agents/voice-agent/endpoint/protocols/voice?api-version=v1", + got, + ) +} + func createSymlinkOrSkip(t *testing.T, oldname, newname string) { t.Helper() From e83f950447b6b083ca591b7c438166125938bcc7 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 10:58:08 +0800 Subject: [PATCH 04/14] fix(agents): validate unified voice response --- .../internal/project/service_target_agent.go | 16 ++++++++++ .../project/service_target_agent_test.go | 30 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 6c0c15c8d15..128fa907d7f 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -2257,6 +2257,9 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( if err != nil { return nil, exterrors.ServiceFromAzure(err, deployOp) } + if err := validateVoiceAgentDeployResponse(agentObject, apiMode); err != nil { + return nil, err + } fmt.Fprintf(os.Stderr, "Voice agent '%s' deployed successfully!\n", agentObject.Name) @@ -2296,6 +2299,19 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( return &azdext.ServiceDeployResult{Artifacts: artifacts}, nil } +func validateVoiceAgentDeployResponse(agentObject *agent_api.AgentObject, apiMode voiceAgentAPIMode) error { + if agentObject == nil { + return fmt.Errorf("malformed voice agent service response: missing agent object") + } + if strings.TrimSpace(agentObject.Name) == "" { + return fmt.Errorf("malformed voice agent service response: missing agent name") + } + if apiMode != voiceAgentAPIModeLegacy && strings.TrimSpace(agentObject.Versions.Latest.Version) == "" { + return fmt.Errorf("malformed voice agent service response: missing latest agent version") + } + return nil +} + func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( ctx context.Context, agentClient *agent_api.AgentClient, diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go index c6e339cd615..6c3fa573ed6 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go @@ -718,6 +718,36 @@ func TestBuildVoiceWSProtocolURL(t *testing.T) { ) } +func TestValidateVoiceAgentDeployResponse(t *testing.T) { + t.Run("legacy requires name only", func(t *testing.T) { + err := validateVoiceAgentDeployResponse( + &agent_api.AgentObject{Name: "voice-agent"}, + voiceAgentAPIModeLegacy, + ) + require.NoError(t, err) + }) + + t.Run("unified requires latest version", func(t *testing.T) { + agent := &agent_api.AgentObject{Name: "voice-agent"} + agent.Versions.Latest.Version = "1" + err := validateVoiceAgentDeployResponse(agent, voiceAgentAPIModeUnifiedFlat) + require.NoError(t, err) + }) + + t.Run("missing name rejected", func(t *testing.T) { + err := validateVoiceAgentDeployResponse(&agent_api.AgentObject{}, voiceAgentAPIModeLegacy) + require.ErrorContains(t, err, "missing agent name") + }) + + t.Run("unified missing version rejected", func(t *testing.T) { + err := validateVoiceAgentDeployResponse( + &agent_api.AgentObject{Name: "voice-agent"}, + voiceAgentAPIModeUnified, + ) + require.ErrorContains(t, err, "missing latest agent version") + }) +} + func createSymlinkOrSkip(t *testing.T, oldname, newname string) { t.Helper() From 048ff7157ae2af1202b81e570658d12c6ca6e312 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 12:13:37 +0800 Subject: [PATCH 05/14] fix(agents): address unified voice review feedback --- .../internal/cmd/nextstep/state.go | 27 ++++++------ .../internal/cmd/nextstep/state_test.go | 23 +++++++++-- .../pkg/agents/agent_yaml/map_voice_test.go | 41 +++++++++++++++++++ .../internal/project/service_target_agent.go | 5 +-- 4 files changed, 75 insertions(+), 21 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go index 5ffe129eeb1..afafade125c 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go +++ b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go @@ -822,23 +822,22 @@ func isDeployed( *errs = append(*errs, fmt.Errorf("read %s: %w", key, err)) return false } - if value != "" { - return true - } - - // Voice agents (kind: prompt-voice) deploy without an agent-version object, - // so they never set AGENT__VERSION. Fall back to the base endpoint - // marker, which every voice deploy writes, so a successfully created voice - // agent is not reported as undeployed. Gate this on the service's actual - // declared kind: a hosted agent whose deploy partially failed can also - // present an empty VERSION with a lingering ENDPOINT, and must stay reported - // as not-deployed. This mirrors the kind gate in + if !isVoice { + return value != "" + } + + // Voice deploys use the base ENDPOINT env var as the completion marker. The + // legacy voice API does not produce AGENT__VERSION, and unified voice + // deploys write VERSION before ENDPOINT to keep ENDPOINT as the final marker. + // Require ENDPOINT for voice even when VERSION is present, otherwise a partial + // env write could be reported as deployed before the callable endpoint was + // persisted. Gate this on the service's actual declared kind: a hosted agent + // whose deploy partially failed can also present an empty VERSION with a + // lingering ENDPOINT, and must stay reported as not-deployed. This mirrors the + // kind gate in // AgentServiceTargetProvider.Endpoints (project package); the two live in // separate packages because project imports nextstep, so a literally shared // helper would create an import cycle. - if !isVoice { - return false - } endpointKey := fmt.Sprintf(agentEndpointVarFormat, serviceKey(serviceName)) endpointValue, err := src.EnvValue(ctx, envName, endpointKey) if err != nil { diff --git a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state_test.go b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state_test.go index c62408b10bf..7f50fe6f190 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state_test.go @@ -739,10 +739,10 @@ func TestServiceKey(t *testing.T) { } } -// TestIsDeployed_VoiceEndpointFallback verifies that a voice agent — which sets -// only AGENT__NAME and AGENT__ENDPOINT, never AGENT__VERSION — is -// still reported as deployed via the base endpoint marker, while an agent with -// neither version nor endpoint is reported undeployed. +// TestIsDeployed_VoiceEndpointFallback verifies that voice readiness is based +// on the base endpoint marker. Legacy voice agents never set VERSION, while +// unified voice agents set VERSION before ENDPOINT; in both cases ENDPOINT is +// the deploy completion marker. func TestIsDeployed_VoiceEndpointFallback(t *testing.T) { t.Parallel() @@ -757,6 +757,21 @@ func TestIsDeployed_VoiceEndpointFallback(t *testing.T) { values: map[string]string{"env1/AGENT_VOICE_SVC_VERSION": "1"}, want: true, }, + { + name: "version set but endpoint missing: undeployed (voice agent partial write)", + values: map[string]string{"env1/AGENT_VOICE_SVC_VERSION": "1"}, + isVoice: true, + want: false, + }, + { + name: "version and endpoint set: deployed (unified voice agent)", + values: map[string]string{ + "env1/AGENT_VOICE_SVC_VERSION": "1", + "env1/AGENT_VOICE_SVC_ENDPOINT": "wss://x/agents/a/endpoint/protocols/voice?api-version=v1", + }, + isVoice: true, + want: true, + }, { name: "no version but base endpoint set: deployed (voice agent)", values: map[string]string{"env1/AGENT_VOICE_SVC_ENDPOINT": "https://x/voice_agents/a"}, diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go index 2ce594e1fbf..1e536b344da 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go @@ -4,6 +4,7 @@ package agent_yaml import ( + "encoding/json" "testing" "azureaiagent/internal/pkg/agents/agent_api" @@ -222,6 +223,46 @@ func TestCreateVoiceAgentAPIRequestFlat_AzureVoiceLocale(t *testing.T) { } } +func TestCreateVoiceAgentAPIRequestFlat_MarshalWireShape(t *testing.T) { + t.Parallel() + voice := "en-US-Ava:DragonHDLatestNeural" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-flat"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &voice, + } + + req, err := CreateVoiceAgentAPIRequestFlat(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + payload, err := json.Marshal(req) + if err != nil { + t.Fatalf("marshal request: %v", err) + } + + var wire map[string]any + if err := json.Unmarshal(payload, &wire); err != nil { + t.Fatalf("unmarshal payload: %v", err) + } + definition := wire["definition"].(map[string]any) + audio := definition["audio"].(map[string]any) + output := audio["output"].(map[string]any) + + if got, ok := output["voice"].(string); !ok || got != voice { + t.Fatalf("audio.output.voice = %#v, want string %q", output["voice"], voice) + } + if got := output["voice_type"]; got != "azure-standard" { + t.Fatalf("audio.output.voice_type = %#v, want azure-standard", got) + } + if got := output["voice_locale"]; got != "en-US" { + t.Fatalf("audio.output.voice_locale = %#v, want en-US", got) + } + if _, exists := output["type"]; exists { + t.Fatalf("audio.output.type should not be present in flat wire shape: %#v", output) + } +} + // TestCreateVoiceAgentAPIRequest_ExplicitManaged verifies that explicitly // setting model_type: managed is accepted (idempotent with the default). func TestCreateVoiceAgentAPIRequest_ExplicitManaged(t *testing.T) { diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 128fa907d7f..a4558598fcb 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -2218,7 +2218,7 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( apiMode, err := resolveVoiceAgentAPIMode(azdEnv) if err != nil { return nil, exterrors.Validation( - exterrors.CodeInvalidAgentManifest, + exterrors.CodeInvalidParameter, err.Error(), fmt.Sprintf("set %s to legacy, unified, or unified-flat", voiceAgentAPIEnvKey), ) @@ -2341,8 +2341,7 @@ func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( return agentObject, exterrors.OpUpdateAgent, err } if getErr != nil { - var respErr *azcore.ResponseError - if !errors.As(getErr, &respErr) || respErr.StatusCode != http.StatusNotFound { + if respErr, ok := errors.AsType[*azcore.ResponseError](getErr); !ok || respErr.StatusCode != http.StatusNotFound { return nil, exterrors.OpCreateAgent, getErr } } From 5d5daef9a6397a06a051a38252c878d174dd3358 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Fri, 21 Aug 2026 13:30:00 +0800 Subject: [PATCH 06/14] fix(agents): address unified voice review feedback --- cli/azd/extensions/azure.ai.agents/README.md | 31 ------------------- .../internal/project/service_target_agent.go | 21 +++++++++---- .../project/service_target_agent_test.go | 27 ++++++++++++++++ 3 files changed, 42 insertions(+), 37 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/README.md b/cli/azd/extensions/azure.ai.agents/README.md index 3108c24e5b7..4ddac596f9a 100644 --- a/cli/azd/extensions/azure.ai.agents/README.md +++ b/cli/azd/extensions/azure.ai.agents/README.md @@ -133,37 +133,6 @@ Details: > the other inline agent properties such as `codeConfiguration` and > `environmentVariables`. -## Prompt voice agent API mode - -Prompt voice agents (`kind: prompt-voice`) use the legacy `/voice_agents` API by -default while the unified `/agents` voice API rolls out across regions. To run -regression tests against the unified API, set `AZURE_VOICE_AGENT_API` before -`azd deploy`: - -```bash -# Default: legacy /voice_agents API -azd env set AZURE_VOICE_AGENT_API legacy - -# Unified /agents API using the current object-shaped audio.output.voice payload -azd env set AZURE_VOICE_AGENT_API unified - -# Unified /agents API using the TiP/spec flat audio.output.voice payload -azd env set AZURE_VOICE_AGENT_API unified-flat -``` - -Details: - -- `legacy` remains the default and preserves existing behavior. -- `unified` and `unified-flat` check `/agents/{name}` remotely before deploying: - `404` creates through `/agents`, while `200` updates through `/agents/{name}`. -- Unified modes write `AGENT__VERSION` and store the callable voice - WebSocket endpoint as `wss://.../agents/{name}/endpoint/protocols/voice?api-version=v1`. -- `legacy` clears any stale `AGENT__VERSION` value and preserves the - existing `/voice_agents/{name}` endpoint marker. -- `unified-flat` is intended for TiP/new-service validation. Non-TiP regions may - still require `legacy` or `unified` until the flat output shape is fully - rolled out. - ### Moderating invocations-protocol traffic For agents that expose the `invocations` protocol, the RAI policy alone is not diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index a4558598fcb..3b01eb4a811 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -2330,7 +2330,11 @@ func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( remoteAgent, getErr := agentClient.GetVoiceAgentUnified( ctx, request.Name, agent_api.AgentEndpointAPIVersion, overriddenHost, ) - if getErr == nil && remoteAgent != nil { + shouldUpdate, decisionErr := shouldUpdateVoiceAgent(remoteAgent, getErr) + if decisionErr != nil { + return nil, exterrors.OpCreateAgent, decisionErr + } + if shouldUpdate { progress("Updating voice agent using unified API") updateRequest := &agent_api.UpdateAgentRequest{ CreateAgentVersionRequest: request.CreateAgentVersionRequest, @@ -2340,17 +2344,22 @@ func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( ) return agentObject, exterrors.OpUpdateAgent, err } - if getErr != nil { - if respErr, ok := errors.AsType[*azcore.ResponseError](getErr); !ok || respErr.StatusCode != http.StatusNotFound { - return nil, exterrors.OpCreateAgent, getErr - } - } progress("Creating voice agent using unified API") agentObject, err := agentClient.CreateVoiceAgentUnified(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) return agentObject, exterrors.OpCreateAgent, err } +func shouldUpdateVoiceAgent(remoteAgent *agent_api.AgentObject, getErr error) (bool, error) { + if getErr == nil { + return remoteAgent != nil, nil + } + if respErr, ok := errors.AsType[*azcore.ResponseError](getErr); ok && respErr.StatusCode == http.StatusNotFound { + return false, nil + } + return false, getErr +} + func voiceAgentEndpoint(projectEndpoint string, agentName string, apiMode voiceAgentAPIMode) string { trimmedEndpoint := strings.TrimRight(projectEndpoint, "/") if apiMode == voiceAgentAPIModeLegacy { diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go index 69921a0328c..bd4d87fa290 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net" + "net/http" "os" "path/filepath" "strings" @@ -748,6 +749,32 @@ func TestValidateVoiceAgentDeployResponse(t *testing.T) { }) } +func TestShouldUpdateVoiceAgent(t *testing.T) { + t.Run("remote found updates", func(t *testing.T) { + update, err := shouldUpdateVoiceAgent(&agent_api.AgentObject{Name: "voice"}, nil) + require.NoError(t, err) + require.True(t, update) + }) + + t.Run("remote nil creates", func(t *testing.T) { + update, err := shouldUpdateVoiceAgent(nil, nil) + require.NoError(t, err) + require.False(t, update) + }) + + t.Run("not found creates", func(t *testing.T) { + update, err := shouldUpdateVoiceAgent(nil, &azcore.ResponseError{StatusCode: http.StatusNotFound}) + require.NoError(t, err) + require.False(t, update) + }) + + t.Run("other get error returns error", func(t *testing.T) { + update, err := shouldUpdateVoiceAgent(nil, &azcore.ResponseError{StatusCode: http.StatusInternalServerError}) + require.Error(t, err) + require.False(t, update) + }) +} + func createSymlinkOrSkip(t *testing.T, oldname, newname string) { t.Helper() From 348edb407ea5d85cedd1714c11b72d04db52a626 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Mon, 24 Aug 2026 16:35:29 +0800 Subject: [PATCH 07/14] refactor(agents): use unified voice API by default --- .../internal/pkg/agents/agent_api/models.go | 13 ++- .../pkg/agents/agent_api/operations.go | 29 ----- .../pkg/agents/agent_api/operations_test.go | 64 ----------- .../internal/pkg/agents/agent_yaml/map.go | 49 +++------ .../pkg/agents/agent_yaml/map_voice_test.go | 20 ++-- .../internal/project/service_target_agent.go | 102 +++--------------- .../project/service_target_agent_test.go | 59 +--------- 7 files changed, 50 insertions(+), 286 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go index 9fedb6e56e3..946ac70951d 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go @@ -69,10 +69,9 @@ const ( AgentKindHosted AgentKind = "hosted" AgentKindWorkflow AgentKind = "workflow" // AgentKindVoice is the data-plane (service) kind for a declarative voice - // (speech-to-speech) agent. Note: this is the wire value posted to the - // /voice_agents collection. The azd manifest authoring kind is - // "prompt-voice" (agent_yaml.AgentKindPromptVoice), which the map layer - // translates to this value. + // (speech-to-speech) agent. The azd manifest authoring kind is "prompt-voice" + // (agent_yaml.AgentKindPromptVoice), which the map layer translates to this + // value before posting through the unified /agents API. AgentKindVoice AgentKind = "voice" ) @@ -420,9 +419,9 @@ type VoiceAudioConfigFlat struct { Output *VoiceOutputConfigFlat `json:"output,omitempty"` } -// VoiceAgentDefinition is the data-plane definition body POSTed to the -// /voice_agents collection for a declarative (managed) voice agent. Its Kind -// is always AgentKindVoice ("voice"). +// VoiceAgentDefinition is retained for compatibility with object-shaped voice +// definitions returned by older services. New prompt voice deploys use +// VoiceAgentDefinitionFlat. type VoiceAgentDefinition struct { AgentDefinition ModelType VoiceModelType `json:"model_type"` diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go index fbd6f514ef3..ce9aff37322 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go @@ -216,35 +216,6 @@ func (c *AgentClient) doVoiceJSONAgentRequest( return &agent, nil } -// CreateVoiceAgent creates a new declarative (managed) voice agent. -// -// Voice agents live in a separate data-plane collection (/voice_agents), distinct -// from the /agents collection used by hosted/workflow agents. The request -// Definition must be a *VoiceAgentDefinition (service kind "voice"). -// -// overriddenHost, when non-empty, is sent as the x-ms-overridden-host header. -// This routes the request directly to the regional Hyena data-plane host, -// bypassing the public Foundry APIM (whose voice route may not yet be rolled -// out). Pass "" to use the default endpoint routing. -// -// Redeploy semantics: the voice data-plane exposes create-only POST /voice_agents -// with no version/upsert model (unlike hosted agents, which mint a new -// agent-version per deploy). A second `azd deploy` of the same voice service -// therefore re-POSTs with the same name and the service rejects it with a -// non-success status, which this method surfaces as a deploy error rather than -// silently overwriting the existing agent. Idempotent redeploy/update is tracked -// as a follow-up (see the PR "Follow-ups" section); until the service adds an -// update route, redeploy requires deleting the existing voice agent first. -func (c *AgentClient) CreateVoiceAgent( - ctx context.Context, - request *CreateAgentRequest, - apiVersion string, - overriddenHost string, -) (*AgentObject, error) { - url := fmt.Sprintf("%s/voice_agents?api-version=%s", c.endpoint, apiVersion) - return c.doVoiceJSONAgentRequest(ctx, http.MethodPost, url, request, overriddenHost) -} - // GetVoiceAgentUnified retrieves a voice agent through the unified /agents // endpoint with the voice preview opt-in header. Use this instead of GetAgent // when deciding whether to create or update a prompt voice agent. diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go index 7aacd0d7ba5..d47e3a5dee1 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations_test.go @@ -919,35 +919,6 @@ func TestDownloadAgentCode_ReturnsErrorOnNon200(t *testing.T) { require.Error(t, err) } -func TestCreateVoiceAgent_PostsToVoiceCollectionWithPreviewHeader(t *testing.T) { - body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{}}}` - client, transport := newCaptureClient(http.StatusOK, body) - - agent, err := client.CreateVoiceAgent( - t.Context(), - &CreateAgentRequest{Name: "my-voice"}, - AgentEndpointAPIVersion, - "", - ) - - require.NoError(t, err) - require.Equal(t, "my-voice", agent.Name) - - require.Len(t, transport.requests, 1) - req := transport.requests[0] - - require.Equal(t, http.MethodPost, req.Method) - require.Equal(t, "/api/projects/proj/voice_agents", req.URL.Path) - require.Equal(t, AgentEndpointAPIVersion, req.URL.Query().Get("api-version")) - require.Equal(t, voiceAgentsPreviewFeature, req.Header.Get("Foundry-Features")) - // Default routing: no host override. - require.Empty(t, req.Header.Get("x-ms-overridden-host")) - - reqBody, err := io.ReadAll(req.Body) - require.NoError(t, err) - require.Contains(t, string(reqBody), `"name":"my-voice"`) -} - func TestCreateVoiceAgentUnified_PostsToAgentsWithPreviewHeader(t *testing.T) { body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{}}}` client, transport := newCaptureClient(http.StatusOK, body) @@ -1014,38 +985,3 @@ func TestUpdateVoiceAgentUnified_PostsToNamedAgentWithPreviewHeader(t *testing.T require.Equal(t, voiceAgentsPreviewFeature, req.Header.Get("Foundry-Features")) require.Equal(t, "regional.hyena.example.com", req.Header.Get("x-ms-overridden-host")) } - -func TestCreateVoiceAgent_SetsOverriddenHostHeader(t *testing.T) { - client, transport := newCaptureClient(http.StatusCreated, `{"name":"my-voice","versions":{"latest":{}}}`) - - _, err := client.CreateVoiceAgent( - t.Context(), - &CreateAgentRequest{Name: "my-voice"}, - AgentEndpointAPIVersion, - "regional.hyena.example.com", - ) - - require.NoError(t, err) - require.Len(t, transport.requests, 1) - require.Equal( - t, - "regional.hyena.example.com", - transport.requests[0].Header.Get("x-ms-overridden-host"), - ) -} - -func TestCreateVoiceAgent_ReturnsErrorOnNonSuccess(t *testing.T) { - client, _ := newCaptureClient( - http.StatusForbidden, - `{"error":{"code":"preview_feature_required","message":"voice agents preview"}}`, - ) - - _, err := client.CreateVoiceAgent( - t.Context(), - &CreateAgentRequest{Name: "my-voice"}, - AgentEndpointAPIVersion, - "", - ) - - require.Error(t, err) -} diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go index 42b1463fb05..b2c9ae5cb9d 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go @@ -608,16 +608,18 @@ func flatVoiceLocale(voice *agent_api.VoiceConfig) string { // voice agent. It translates the authoring kind "prompt-voice" into the // data-plane service kind "voice" and defaults the audio pipeline. func CreateVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { - return createVoiceAgentAPIRequest(voiceAgent, false) + return createVoiceAgentAPIRequest(voiceAgent) } -// CreateVoiceAgentAPIRequestFlat builds a CreateAgentRequest using the newer -// TiP/unified API flat output voice shape. +// CreateVoiceAgentAPIRequestFlat is kept as a compatibility wrapper for tests +// and callers that explicitly selected the transition name while the unified API +// work was in flight. Prompt voice requests now always use the unified flat +// output shape. func CreateVoiceAgentAPIRequestFlat(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { - return createVoiceAgentAPIRequest(voiceAgent, true) + return createVoiceAgentAPIRequest(voiceAgent) } -func createVoiceAgentAPIRequest(voiceAgent VoiceAgent, flatOutput bool) (*agent_api.CreateAgentRequest, error) { +func createVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { modelID := "" if voiceAgent.Model != nil { modelID = strings.TrimSpace(voiceAgent.Model.Id) @@ -657,32 +659,7 @@ func createVoiceAgentAPIRequest(voiceAgent VoiceAgent, flatOutput bool) (*agent_ Transcription: &agent_api.VoiceTranscription{Model: defaultVoiceInputTranscriptionModel}, } voiceConfig := buildVoiceConfig(voiceName) - if flatOutput { - voiceDef := agent_api.VoiceAgentDefinitionFlat{ - AgentDefinition: agent_api.AgentDefinition{ - // Translate authoring kind prompt-voice -> service kind voice. - Kind: agent_api.AgentKindVoice, - }, - ModelType: modelType, - Model: modelID, - Instructions: instructions, - Audio: &agent_api.VoiceAudioConfigFlat{ - Input: input, - Output: &agent_api.VoiceOutputConfigFlat{ - Format: audioFormat, - Voice: voiceConfig.Name, - VoiceType: flatVoiceType(voiceConfig), - VoiceLocale: flatVoiceLocale(voiceConfig), - }, - }, - OutputModalities: []string{"audio"}, - Store: voiceAgent.Store, - } - - return createAgentAPIRequest(voiceAgent.AgentDefinition, voiceDef, nil, nil) - } - - voiceDef := agent_api.VoiceAgentDefinition{ + voiceDef := agent_api.VoiceAgentDefinitionFlat{ AgentDefinition: agent_api.AgentDefinition{ // Translate authoring kind prompt-voice -> service kind voice. Kind: agent_api.AgentKindVoice, @@ -690,11 +667,13 @@ func createVoiceAgentAPIRequest(voiceAgent VoiceAgent, flatOutput bool) (*agent_ ModelType: modelType, Model: modelID, Instructions: instructions, - Audio: &agent_api.VoiceAudioConfig{ + Audio: &agent_api.VoiceAudioConfigFlat{ Input: input, - Output: &agent_api.VoiceOutputConfig{ - Format: audioFormat, - Voice: voiceConfig, + Output: &agent_api.VoiceOutputConfigFlat{ + Format: audioFormat, + Voice: voiceConfig.Name, + VoiceType: flatVoiceType(voiceConfig), + VoiceLocale: flatVoiceLocale(voiceConfig), }, }, OutputModalities: []string{"audio"}, diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go index 1e536b344da..4b6e78ae065 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go @@ -90,9 +90,9 @@ func TestCreateVoiceAgentAPIRequest_Defaults(t *testing.T) { t.Errorf("Name = %q", req.Name) } - def, ok := req.Definition.(agent_api.VoiceAgentDefinition) + def, ok := req.Definition.(agent_api.VoiceAgentDefinitionFlat) if !ok { - t.Fatalf("expected VoiceAgentDefinition, got %T", req.Definition) + t.Fatalf("expected VoiceAgentDefinitionFlat, got %T", req.Definition) } // Authoring kind prompt-voice is translated to service kind voice. @@ -131,9 +131,9 @@ func TestCreateVoiceAgentAPIRequest_Defaults(t *testing.T) { if out.Format == nil || out.Format.Type != defaultVoiceAudioType || out.Format.Rate != defaultVoiceAudioRate { t.Errorf("output format = %+v", out.Format) } - // Default voice is the DragonHD Azure Neural voice. - if out.Voice == nil || out.Voice.Type != "azure_standard" || out.Voice.Name != defaultVoiceName { - t.Errorf("output voice = %+v, want azure_standard/%s", out.Voice, defaultVoiceName) + // Default voice is the DragonHD Azure Neural voice in the flat unified shape. + if out.Voice != defaultVoiceName || out.VoiceType != "azure-standard" || out.VoiceLocale != "en-US" { + t.Errorf("output voice = %+v, want azure-standard/%s", out, defaultVoiceName) } // Store defaults to nil (service defaults to false). if def.Store != nil { @@ -160,12 +160,12 @@ func TestCreateVoiceAgentAPIRequest_Overrides(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - def := req.Definition.(agent_api.VoiceAgentDefinition) + def := req.Definition.(agent_api.VoiceAgentDefinitionFlat) if def.Instructions != instructions { t.Errorf("Instructions = %q", def.Instructions) } // "alloy" is an OpenAI realtime voice. - if def.Audio.Output.Voice.Type != "openai" || def.Audio.Output.Voice.Name != "alloy" { + if def.Audio.Output.VoiceType != "openai" || def.Audio.Output.Voice != "alloy" { t.Errorf("voice = %+v, want openai/alloy", def.Audio.Output.Voice) } if def.Store == nil || !*def.Store { @@ -276,7 +276,7 @@ func TestCreateVoiceAgentAPIRequest_ExplicitManaged(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - if req.Definition.(agent_api.VoiceAgentDefinition).ModelType != agent_api.VoiceModelTypeManaged { + if req.Definition.(agent_api.VoiceAgentDefinitionFlat).ModelType != agent_api.VoiceModelTypeManaged { t.Errorf("ModelType not managed") } } @@ -304,7 +304,7 @@ func TestCreateVoiceAgentAPIRequest_TrimsModelID(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - def := req.Definition.(agent_api.VoiceAgentDefinition) + def := req.Definition.(agent_api.VoiceAgentDefinitionFlat) if def.Model != "my-realtime-deployment" { t.Errorf("Model = %q, want trimmed model id", def.Model) } @@ -334,7 +334,7 @@ func TestCreateVoiceAgentAPIRequest_SelfDeployedMapped(t *testing.T) { if err != nil { t.Fatalf("unexpected error: %v", err) } - def := req.Definition.(agent_api.VoiceAgentDefinition) + def := req.Definition.(agent_api.VoiceAgentDefinitionFlat) if def.ModelType != agent_api.VoiceModelTypeSelfDeployed { t.Errorf("ModelType = %q, want self_deployed", def.ModelType) } diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 3b01eb4a811..51f590ce0cf 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -2155,57 +2155,17 @@ func (p *AgentServiceTargetProvider) deployHostedAgent( }, nil } -// voiceOverriddenHostEnvKey optionally routes the /voice_agents call directly to -// a regional data-plane host (bypassing the public Foundry APIM, whose voice -// route may not yet be rolled out). When unset, default endpoint routing is used. +// voiceOverriddenHostEnvKey optionally routes prompt voice agent calls directly +// to a regional data-plane host (bypassing the public Foundry APIM when needed). +// When unset, default endpoint routing is used. // //nolint:gosec // env var key name, not a credential const voiceOverriddenHostEnvKey = "AZURE_VOICE_OVERRIDDEN_HOST" -// voiceAgentAPIEnvKey controls which voice deployment API azd uses. It defaults -// to the legacy /voice_agents path while the unified API rolls out regionally. -// Supported values: -// - legacy: POST /voice_agents with object-shaped audio.output.voice -// - unified: POST /agents or /agents/{name} with object-shaped audio.output.voice -// - unified-flat: POST /agents or /agents/{name} with flat audio.output.voice -// -//nolint:gosec // env var key name, not a credential -const voiceAgentAPIEnvKey = "AZURE_VOICE_AGENT_API" - -type voiceAgentAPIMode string - -const ( - voiceAgentAPIModeLegacy voiceAgentAPIMode = "legacy" - voiceAgentAPIModeUnified voiceAgentAPIMode = "unified" - voiceAgentAPIModeUnifiedFlat voiceAgentAPIMode = "unified-flat" -) - -func resolveVoiceAgentAPIMode(azdEnv map[string]string) (voiceAgentAPIMode, error) { - mode := strings.TrimSpace(azdEnv[voiceAgentAPIEnvKey]) - if mode == "" { - mode = strings.TrimSpace(os.Getenv(voiceAgentAPIEnvKey)) - } - mode = strings.ToLower(strings.ReplaceAll(mode, "_", "-")) - if mode == "" { - return voiceAgentAPIModeLegacy, nil - } - switch voiceAgentAPIMode(mode) { - case voiceAgentAPIModeLegacy, voiceAgentAPIModeUnified, voiceAgentAPIModeUnifiedFlat: - return voiceAgentAPIMode(mode), nil - default: - return "", fmt.Errorf( - "%s must be one of %q, %q, or %q", - voiceAgentAPIEnvKey, voiceAgentAPIModeLegacy, voiceAgentAPIModeUnified, voiceAgentAPIModeUnifiedFlat, - ) - } -} - // deployVoiceAgent deploys a declarative (managed) voice agent (kind: -// prompt-voice) to the Foundry service. The legacy /voice_agents API remains -// the default while unified /agents rolls out regionally; AZURE_VOICE_AGENT_API -// can opt into unified modes for regression and TiP validation. This method is -// intentionally isolated from the container deploy path so the two contracts -// never entangle. +// prompt-voice) to the Foundry service through the unified /agents API. This +// method is intentionally isolated from the container deploy path so the two +// contracts never entangle. func (p *AgentServiceTargetProvider) deployVoiceAgent( ctx context.Context, serviceConfig *azdext.ServiceConfig, @@ -2215,21 +2175,7 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( ) (*azdext.ServiceDeployResult, error) { progress("Deploying voice agent") - apiMode, err := resolveVoiceAgentAPIMode(azdEnv) - if err != nil { - return nil, exterrors.Validation( - exterrors.CodeInvalidParameter, - err.Error(), - fmt.Sprintf("set %s to legacy, unified, or unified-flat", voiceAgentAPIEnvKey), - ) - } - - var request *agent_api.CreateAgentRequest - if apiMode == voiceAgentAPIModeUnifiedFlat { - request, err = agent_yaml.CreateVoiceAgentAPIRequestFlat(va) - } else { - request, err = agent_yaml.CreateVoiceAgentAPIRequest(va) - } + request, err := agent_yaml.CreateVoiceAgentAPIRequestFlat(va) if err != nil { return nil, exterrors.Validation( exterrors.CodeInvalidAgentManifest, @@ -2251,13 +2197,13 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( agentClient := agent_api.NewAgentClient(projectEndpoint, p.credential) serviceKey := p.getServiceKey(serviceConfig.Name) - agentObject, deployOp, err := p.deployVoiceAgentWithMode( - ctx, agentClient, request, apiMode, azdEnv, progress, + agentObject, deployOp, err := p.deployVoiceAgentUnified( + ctx, agentClient, request, azdEnv, progress, ) if err != nil { return nil, exterrors.ServiceFromAzure(err, deployOp) } - if err := validateVoiceAgentDeployResponse(agentObject, apiMode); err != nil { + if err := validateVoiceAgentDeployResponse(agentObject); err != nil { return nil, err } @@ -2265,12 +2211,9 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( // Persist NAME first and ENDPOINT last. ENDPOINT is used as the voice deploy // completion marker by other commands, so avoid writing it before NAME. - baseEndpoint := voiceAgentEndpoint(projectEndpoint, agentObject.Name, apiMode) + baseEndpoint := buildVoiceWSProtocolURL(projectEndpoint, agentObject.Name) versionKey := fmt.Sprintf("AGENT_%s_VERSION", serviceKey) - versionValue := "" - if apiMode != voiceAgentAPIModeLegacy { - versionValue = agentObject.Versions.Latest.Version - } + versionValue := agentObject.Versions.Latest.Version for _, envVar := range []struct{ key, value string }{ {fmt.Sprintf("AGENT_%s_NAME", serviceKey), agentObject.Name}, {versionKey, versionValue}, @@ -2299,34 +2242,27 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( return &azdext.ServiceDeployResult{Artifacts: artifacts}, nil } -func validateVoiceAgentDeployResponse(agentObject *agent_api.AgentObject, apiMode voiceAgentAPIMode) error { +func validateVoiceAgentDeployResponse(agentObject *agent_api.AgentObject) error { if agentObject == nil { return fmt.Errorf("malformed voice agent service response: missing agent object") } if strings.TrimSpace(agentObject.Name) == "" { return fmt.Errorf("malformed voice agent service response: missing agent name") } - if apiMode != voiceAgentAPIModeLegacy && strings.TrimSpace(agentObject.Versions.Latest.Version) == "" { + if strings.TrimSpace(agentObject.Versions.Latest.Version) == "" { return fmt.Errorf("malformed voice agent service response: missing latest agent version") } return nil } -func (p *AgentServiceTargetProvider) deployVoiceAgentWithMode( +func (p *AgentServiceTargetProvider) deployVoiceAgentUnified( ctx context.Context, agentClient *agent_api.AgentClient, request *agent_api.CreateAgentRequest, - apiMode voiceAgentAPIMode, azdEnv map[string]string, progress azdext.ProgressReporter, ) (*agent_api.AgentObject, string, error) { overriddenHost := azdEnv[voiceOverriddenHostEnvKey] - if apiMode == voiceAgentAPIModeLegacy { - progress("Creating voice agent using legacy API") - agentObject, err := agentClient.CreateVoiceAgent(ctx, request, agent_api.AgentEndpointAPIVersion, overriddenHost) - return agentObject, exterrors.OpCreateAgent, err - } - remoteAgent, getErr := agentClient.GetVoiceAgentUnified( ctx, request.Name, agent_api.AgentEndpointAPIVersion, overriddenHost, ) @@ -2360,14 +2296,6 @@ func shouldUpdateVoiceAgent(remoteAgent *agent_api.AgentObject, getErr error) (b return false, getErr } -func voiceAgentEndpoint(projectEndpoint string, agentName string, apiMode voiceAgentAPIMode) string { - trimmedEndpoint := strings.TrimRight(projectEndpoint, "/") - if apiMode == voiceAgentAPIModeLegacy { - return fmt.Sprintf("%s/voice_agents/%s", trimmedEndpoint, agentName) - } - return buildVoiceWSProtocolURL(trimmedEndpoint, agentName) -} - // packageCodeDeploy creates a ZIP archive of the agent source code, writes it to a temp file, // and computes its SHA-256. Returns the temp file path and SHA-256 hex string. func (p *AgentServiceTargetProvider) packageCodeDeploy(ctx context.Context, serviceConfig *azdext.ServiceConfig) (string, string, error) { diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go index bd4d87fa290..925c9de1256 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go @@ -669,44 +669,6 @@ func TestAdoptServiceConfigIgnoresNilAndKeepsResolvedState(t *testing.T) { require.False(t, provider.serviceConfigResolved) } -func TestResolveVoiceAgentAPIMode_DefaultsToLegacy(t *testing.T) { - t.Setenv(voiceAgentAPIEnvKey, "") - mode, err := resolveVoiceAgentAPIMode(map[string]string{}) - require.NoError(t, err) - require.Equal(t, voiceAgentAPIModeLegacy, mode) -} - -func TestResolveVoiceAgentAPIMode_EnvValues(t *testing.T) { - t.Setenv(voiceAgentAPIEnvKey, "unified_flat") - mode, err := resolveVoiceAgentAPIMode(map[string]string{}) - require.NoError(t, err) - require.Equal(t, voiceAgentAPIModeUnifiedFlat, mode) - - mode, err = resolveVoiceAgentAPIMode(map[string]string{voiceAgentAPIEnvKey: "unified"}) - require.NoError(t, err) - require.Equal(t, voiceAgentAPIModeUnified, mode) -} - -func TestResolveVoiceAgentAPIMode_Invalid(t *testing.T) { - _, err := resolveVoiceAgentAPIMode(map[string]string{voiceAgentAPIEnvKey: "future"}) - require.Error(t, err) - require.Contains(t, err.Error(), voiceAgentAPIEnvKey) -} - -func TestVoiceAgentEndpoint_ByMode(t *testing.T) { - projectEndpoint := "https://proj.services.ai.azure.com/api/projects/p/" - require.Equal( - t, - "https://proj.services.ai.azure.com/api/projects/p/voice_agents/my-agent", - voiceAgentEndpoint(projectEndpoint, "my-agent", voiceAgentAPIModeLegacy), - ) - require.Equal( - t, - "wss://proj.services.ai.azure.com/api/projects/p/agents/my-agent/endpoint/protocols/voice?api-version=v1", - voiceAgentEndpoint(projectEndpoint, "my-agent", voiceAgentAPIModeUnified), - ) -} - func TestBuildVoiceWSProtocolURL(t *testing.T) { got := buildVoiceWSProtocolURL( "https://acct.services.ai.azure.com/api/projects/proj/", @@ -720,31 +682,20 @@ func TestBuildVoiceWSProtocolURL(t *testing.T) { } func TestValidateVoiceAgentDeployResponse(t *testing.T) { - t.Run("legacy requires name only", func(t *testing.T) { - err := validateVoiceAgentDeployResponse( - &agent_api.AgentObject{Name: "voice-agent"}, - voiceAgentAPIModeLegacy, - ) - require.NoError(t, err) - }) - - t.Run("unified requires latest version", func(t *testing.T) { + t.Run("requires name and latest version", func(t *testing.T) { agent := &agent_api.AgentObject{Name: "voice-agent"} agent.Versions.Latest.Version = "1" - err := validateVoiceAgentDeployResponse(agent, voiceAgentAPIModeUnifiedFlat) + err := validateVoiceAgentDeployResponse(agent) require.NoError(t, err) }) t.Run("missing name rejected", func(t *testing.T) { - err := validateVoiceAgentDeployResponse(&agent_api.AgentObject{}, voiceAgentAPIModeLegacy) + err := validateVoiceAgentDeployResponse(&agent_api.AgentObject{}) require.ErrorContains(t, err, "missing agent name") }) - t.Run("unified missing version rejected", func(t *testing.T) { - err := validateVoiceAgentDeployResponse( - &agent_api.AgentObject{Name: "voice-agent"}, - voiceAgentAPIModeUnified, - ) + t.Run("missing version rejected", func(t *testing.T) { + err := validateVoiceAgentDeployResponse(&agent_api.AgentObject{Name: "voice-agent"}) require.ErrorContains(t, err, "missing latest agent version") }) } From 3c733352b7e757e0cc0336a671cba2402f9d458a Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Mon, 24 Aug 2026 16:48:12 +0800 Subject: [PATCH 08/14] docs(agents): clarify voice deploy marker --- .../azure.ai.agents/internal/cmd/nextstep/state.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go index afafade125c..768e776e2f9 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go +++ b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go @@ -826,9 +826,9 @@ func isDeployed( return value != "" } - // Voice deploys use the base ENDPOINT env var as the completion marker. The - // legacy voice API does not produce AGENT__VERSION, and unified voice - // deploys write VERSION before ENDPOINT to keep ENDPOINT as the final marker. + // Voice deploys use the base ENDPOINT env var as the completion marker. + // Unified voice deploys write VERSION before ENDPOINT to keep ENDPOINT as the + // final marker. // Require ENDPOINT for voice even when VERSION is present, otherwise a partial // env write could be reported as deployed before the callable endpoint was // persisted. Gate this on the service's actual declared kind: a hosted agent From 62ef41e3f96a700b8ea89d604aa899a8fa550cde Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Mon, 24 Aug 2026 17:14:34 +0800 Subject: [PATCH 09/14] docs(agents): clarify unified voice version state Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: c76c1120-2c86-448b-8ed3-308d53db7dac --- .../cmd/doctor/checks_agent_status.go | 7 ++++--- .../internal/cmd/nextstep/state.go | 6 +++--- .../internal/project/service_target_agent.go | 19 ++++++++++--------- .../project/service_target_agent_test.go | 18 +++++++++--------- 4 files changed, 26 insertions(+), 24 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/cmd/doctor/checks_agent_status.go b/cli/azd/extensions/azure.ai.agents/internal/cmd/doctor/checks_agent_status.go index cdffffe264d..840792460b8 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/cmd/doctor/checks_agent_status.go +++ b/cli/azd/extensions/azure.ai.agents/internal/cmd/doctor/checks_agent_status.go @@ -704,9 +704,10 @@ func readAgentServices(prior []Result) []string { // filterHostedAgentServices removes prompt-voice services from the hosted-agent // status probe. The remote.agent-status check targets hosted agent versions -// (`/agents/{name}/versions/{version}`) and relies on AGENT__VERSION; a -// prompt-voice deploy writes NAME+ENDPOINT only and should be covered by a -// voice-specific doctor check in a future PR. +// (`/agents/{name}/versions/{version}`). Unified prompt-voice deploys record a +// VERSION, but voice readiness follows its WebSocket endpoint rather than the +// hosted-agent version lifecycle and should be covered by a voice-specific +// doctor check in a future PR. func filterHostedAgentServices(ctx context.Context, azdClient *azdext.AzdClient, services []string) []string { if len(services) == 0 || azdClient == nil { return services diff --git a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go index 768e776e2f9..e06719e3330 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go +++ b/cli/azd/extensions/azure.ai.agents/internal/cmd/nextstep/state.go @@ -36,9 +36,9 @@ const ( agentVersionVarFormat = "AGENT_%s_VERSION" // agentEndpointVarFormat is the base endpoint env-var written for every - // deployed agent. Voice agents (kind: prompt-voice) are created - // synchronously with no agent-version object, so this base endpoint is the - // only deployment marker they set — isDeployed falls back to it. + // deployed agent. Voice agents (kind: prompt-voice) use it as the deploy + // completion marker. Unified voice deploys also set VERSION, while legacy + // voice environments may have only this endpoint marker. agentEndpointVarFormat = "AGENT_%s_ENDPOINT" // projectEndpointVar is the env-var that carries the Foundry project diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 51f590ce0cf..39379969eea 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go @@ -551,15 +551,16 @@ func (p *AgentServiceTargetProvider) Endpoints( agentVersionKey := fmt.Sprintf("AGENT_%s_VERSION", serviceKey) agentEndpointKey := fmt.Sprintf("AGENT_%s_ENDPOINT", serviceKey) - // Voice agents (kind: prompt-voice) are created synchronously with no - // agent-version object and no per-protocol endpoints; they record only NAME - // and a base ENDPOINT. Gate the base-endpoint fallback on the service's - // actual declared kind (resolved via the shared agentkind lookup, so this - // agrees with the deploy path and next-step reader) rather than on the - // env-var shape: a hosted agent whose deploy partially failed (or whose vars - // were cleaned up) can also present an empty VERSION with a lingering - // ENDPOINT, and for that case we must still surface the actionable - // CodeMissingAgentEnvVars error below. Kind resolution is best-effort here: + // Voice agents (kind: prompt-voice) use the base ENDPOINT as their callable + // endpoint and deploy completion marker. Unified deploys also record VERSION, + // while environments created by the legacy voice API may have only + // NAME+ENDPOINT. Gate the base-endpoint path on the service's actual declared + // kind (resolved via the shared agentkind lookup, so this agrees with the + // deploy path and next-step reader) rather than on the env-var shape: a hosted + // agent whose deploy partially failed (or whose vars were cleaned up) can also + // present an empty VERSION with a lingering ENDPOINT, and for that case we + // must still surface the actionable CodeMissingAgentEnvVars error below. + // Kind resolution is best-effort here: // an error (or non-voice result) simply falls through to the hosted guard, so // hosted services keep their prior behavior on a path that never resolved // config before. diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go index 925c9de1256..a3c0af5af9f 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent_test.go @@ -2810,9 +2810,9 @@ func newEndpointsTestClient( // TestEndpoints_VoiceManifestOnDisk_ResolvesProjectRoot covers the fresh-process // case where Endpoints runs without ensureDeployContext having populated // p.projectPath. A legacy-shape prompt-voice service (kind only on disk, no -// inline kind) records NAME+ENDPOINT but no VERSION; Endpoints must resolve the -// project root itself so agentkind classifies it as voice and returns the base -// endpoint instead of the missing-VERSION error. +// inline kind) may retain NAME+ENDPOINT without VERSION from an earlier deploy; +// Endpoints must resolve the project root itself so agentkind classifies it as +// voice and returns the base endpoint instead of the missing-VERSION error. func TestEndpoints_VoiceManifestOnDisk_ResolvesProjectRoot(t *testing.T) { t.Parallel() @@ -2830,7 +2830,7 @@ func TestEndpoints_VoiceManifestOnDisk_ResolvesProjectRoot(t *testing.T) { "FOUNDRY_PROJECT_ENDPOINT": "https://proj.services.ai.azure.com", "AGENT_VOICE_NAME": "my-voice", "AGENT_VOICE_ENDPOINT": endpoint, - // deliberately no AGENT_VOICE_VERSION: voice agents have no version. + // Deliberately model a legacy persisted environment with no VERSION. }) // Fresh process: projectPath/agentDefinitionPath are empty, exactly as they @@ -2848,10 +2848,10 @@ func TestEndpoints_VoiceManifestOnDisk_ResolvesProjectRoot(t *testing.T) { // TestEndpoints_VoiceAgentDefinitionPathOverride covers the fresh-process case // where a voice manifest is supplied via the AGENT_DEFINITION_PATH override. -// Deploy follows the override and writes NAME+ENDPOINT but no VERSION; Endpoints -// runs without ensureDeployContext (so p.agentDefinitionPath is empty) and must -// read the process override to classify the service as voice, rather than -// classifying the (kind-less) service entry and returning missing-VERSION. +// Endpoints runs without ensureDeployContext (so p.agentDefinitionPath is empty) +// and must read the process override to classify a legacy persisted +// NAME+ENDPOINT environment as voice, rather than classifying the (kind-less) +// service entry and returning missing-VERSION. func TestEndpoints_VoiceAgentDefinitionPathOverride(t *testing.T) { projectRoot := t.TempDir() overridePath := filepath.Join(projectRoot, "custom-voice.yaml") @@ -2867,7 +2867,7 @@ func TestEndpoints_VoiceAgentDefinitionPathOverride(t *testing.T) { "FOUNDRY_PROJECT_ENDPOINT": "https://proj.services.ai.azure.com", "AGENT_VOICE_NAME": "my-voice", "AGENT_VOICE_ENDPOINT": endpoint, - // no AGENT_VOICE_VERSION: voice agents have no version. + // Deliberately model a legacy persisted environment with no VERSION. }) // Fresh process: the service entry carries no kind; only the override does. From 31a2860fb6f723542e5513bd6b7706abca68f4c1 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Mon, 24 Aug 2026 19:44:57 +0800 Subject: [PATCH 10/14] docs(agents): clarify unified voice default --- .../azure.ai.agents/internal/pkg/agents/agent_api/operations.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go index ce9aff37322..cfa24decde8 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/operations.go @@ -260,7 +260,7 @@ func (c *AgentClient) GetVoiceAgentUnified( } // CreateVoiceAgentUnified creates a voice agent through the unified /agents -// collection. This path is opt-in while regional rollout is still in progress. +// collection. Prompt voice deploys use this path by default. func (c *AgentClient) CreateVoiceAgentUnified( ctx context.Context, request *CreateAgentRequest, From e78755745dda9a8a3344c808f8c7cf360490fa86 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 14:14:47 +0800 Subject: [PATCH 11/14] feat(agents): support advanced voice settings --- cli/azd/extensions/azure.ai.agents/README.md | 92 +++++++++ .../extensions/azure.ai.agents/cspell.yaml | 3 + .../internal/pkg/agents/agent_api/models.go | 83 ++++++-- .../internal/pkg/agents/agent_yaml/map.go | 192 ++++++++++++++++-- .../pkg/agents/agent_yaml/map_voice_test.go | 102 +++++++++- .../internal/pkg/agents/agent_yaml/parse.go | 69 +++++++ .../internal/pkg/agents/agent_yaml/yaml.go | 89 ++++++++ .../internal/project/agent_definition.go | 67 ++++-- .../schemas/azure.ai.agent.json | 159 +++++++++++++-- 9 files changed, 790 insertions(+), 66 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/README.md b/cli/azd/extensions/azure.ai.agents/README.md index 4ddac596f9a..8dd303f82a6 100644 --- a/cli/azd/extensions/azure.ai.agents/README.md +++ b/cli/azd/extensions/azure.ai.agents/README.md @@ -199,6 +199,98 @@ keys throughout this block (`invocations_moderation`, `response_mode`, `input_paths`, `stream_selectors`, `event_type`, and so on). The **values** (`non_streaming`, `streaming`, `both`, `json`, `text`) are the same in both. +## Prompt voice advanced configuration + +Advanced prompt voice settings are authored on the `azure.ai.agent` service in +`azure.yaml` and require the unified flat API mode: + +```bash +azd env set AZURE_VOICE_AGENT_API unified-flat +``` + +```yaml +services: + voice-agent: + host: azure.ai.agent + kind: prompt-voice + name: voice-agent + modelType: managed # or self_deployed for BYOM + model: + id: gpt-realtime + instructions: You are {{persona}}, a concise voice assistant. + structuredInputs: + persona: + description: Assistant persona + defaultValue: Ada + schema: + type: string + audio: + input: + format: + type: audio/pcmu + noiseReduction: + type: near_field + echoCancellation: + type: server_echo_cancellation + reference_source: server + channels: 1 + turnDetection: + type: azure_semantic_vad + threshold: 0.6 + speechDurationMs: 120 + removeFillerWords: true + createResponse: true + interruptResponse: true + languages: [en-US] + autoTruncate: true + transcription: + model: whisper-1 + language: en-US + output: + format: + type: audio/pcm + rate: 24000 + voice: + type: azure_standard + name: en-US-AvaNeural + locale: en-US + style: cheerful + speed: 1.0 + outputModalities: [audio, text] + tools: + - type: system + name: end_conversation + avatar: + type: video_avatar + character: lisa + style: casual-sitting + output_protocol: webrtc + greeting: + type: template + text: Hello {{persona}} + toolChoice: auto + parallelToolCalls: true + maxOutputTokens: inf + include: + - item.input_audio_transcription.phrases +``` + +Notes: + +- `voice`, `instructions`, and `store` remain supported for simple prompt voice + agents. Missing audio fields keep the existing azd defaults. +- `audio.output.voice` uses an author-friendly object shape; in `unified-flat` + mode azd maps it to the service flat fields `voice`, `voice_type`, + `voice_locale`, `style`, `pitch`, `rate`, and `volume`. +- `structuredInputs.defaultValue` maps to the service wire field + `default_value`. +- Direct voice tool types are `function`, `mcp`, `system`, and `toolbox`. + Server-side tools such as `web_search`, `azure_ai_search`, and `openapi` must + be packaged through a toolbox. +- `tools`, `avatar`, `greeting`, `handoff`, `toolChoice`, and + `echoCancellation` intentionally remain light pass-through blocks so azd does + not block new service-side additions. + ## Session idle timeout A hosted agent's runtime session sandbox is suspended by Foundry after a period diff --git a/cli/azd/extensions/azure.ai.agents/cspell.yaml b/cli/azd/extensions/azure.ai.agents/cspell.yaml index 5d2d9e0950c..78be91d2fea 100644 --- a/cli/azd/extensions/azure.ai.agents/cspell.yaml +++ b/cli/azd/extensions/azure.ai.agents/cspell.yaml @@ -11,6 +11,9 @@ words: # Voice (prompt-voice) agents - BYOM - Nanami + - pcma + - pcmu + - webrtc # Azure region names - australiaeast - brazilsouth diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go index 946ac70951d..caf26a39696 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_api/models.go @@ -359,7 +359,7 @@ const ( // VoiceAudioFormat describes a PCM audio stream format (e.g. audio/pcm @ 24 kHz). type VoiceAudioFormat struct { Type string `json:"type"` - Rate int `json:"rate"` + Rate *int `json:"rate,omitempty"` } // VoiceTurnDetection configures server-side voice-activity detection so the @@ -369,32 +369,54 @@ type VoiceTurnDetection struct { Threshold *float64 `json:"threshold,omitempty"` PrefixPaddingMs *int `json:"prefix_padding_ms,omitempty"` SilenceDurationMs *int `json:"silence_duration_ms,omitempty"` + CreateResponse *bool `json:"create_response,omitempty"` + Eagerness *string `json:"eagerness,omitempty"` + SpeechDurationMs *int `json:"speech_duration_ms,omitempty"` + RemoveFillerWords *bool `json:"remove_filler_words,omitempty"` + InterruptResponse *bool `json:"interrupt_response,omitempty"` + Languages []string `json:"languages,omitempty"` + AutoTruncate *bool `json:"auto_truncate,omitempty"` } // VoiceTranscription enables user-speech transcription events on the input stream. type VoiceTranscription struct { - Model string `json:"model,omitempty"` + Model string `json:"model,omitempty"` + Language *string `json:"language,omitempty"` + Prompt *string `json:"prompt,omitempty"` +} + +// VoiceNoiseReduction configures input audio noise reduction. +type VoiceNoiseReduction struct { + Type string `json:"type"` } // VoiceInputConfig is the input (caller -> agent) audio configuration. type VoiceInputConfig struct { - Format *VoiceAudioFormat `json:"format,omitempty"` - TurnDetection *VoiceTurnDetection `json:"turn_detection,omitempty"` - Transcription *VoiceTranscription `json:"transcription,omitempty"` + Format *VoiceAudioFormat `json:"format,omitempty"` + NoiseReduction *VoiceNoiseReduction `json:"noise_reduction,omitempty"` + EchoCancellation map[string]any `json:"echo_cancellation,omitempty"` + TurnDetection *VoiceTurnDetection `json:"turn_detection,omitempty"` + Transcription *VoiceTranscription `json:"transcription,omitempty"` } // VoiceConfig selects the output voice. Type is "openai" for realtime voices // (single lowercase word, e.g. "alloy") or "azure_standard" for Azure Neural // voices (e.g. "en-US-Ava:DragonHDLatestNeural"). type VoiceConfig struct { - Type string `json:"type"` - Name string `json:"name"` + Type string `json:"type"` + Name string `json:"name"` + Style *string `json:"style,omitempty"` + Pitch *string `json:"pitch,omitempty"` + Rate *string `json:"rate,omitempty"` + Locale *string `json:"locale,omitempty"` + Volume *string `json:"volume,omitempty"` } // VoiceOutputConfig is the output (agent -> caller) audio configuration. type VoiceOutputConfig struct { Format *VoiceAudioFormat `json:"format,omitempty"` Voice *VoiceConfig `json:"voice,omitempty"` + Speed *float64 `json:"speed,omitempty"` } // VoiceOutputConfigFlat is the newer Voice Live output shape used by the @@ -405,6 +427,11 @@ type VoiceOutputConfigFlat struct { Voice string `json:"voice,omitempty"` VoiceType string `json:"voice_type,omitempty"` VoiceLocale string `json:"voice_locale,omitempty"` + Style *string `json:"style,omitempty"` + Pitch *string `json:"pitch,omitempty"` + Rate *string `json:"rate,omitempty"` + Volume *string `json:"volume,omitempty"` + Speed *float64 `json:"speed,omitempty"` } // VoiceAudioConfig bundles the input and output audio configuration. @@ -424,12 +451,21 @@ type VoiceAudioConfigFlat struct { // VoiceAgentDefinitionFlat. type VoiceAgentDefinition struct { AgentDefinition - ModelType VoiceModelType `json:"model_type"` - Model string `json:"model"` - Instructions string `json:"instructions,omitempty"` - Audio *VoiceAudioConfig `json:"audio,omitempty"` - OutputModalities []string `json:"output_modalities,omitempty"` - Store *bool `json:"store,omitempty"` + ModelType VoiceModelType `json:"model_type"` + Model string `json:"model"` + Instructions string `json:"instructions,omitempty"` + StructuredInputs map[string]any `json:"structured_inputs,omitempty"` + Audio *VoiceAudioConfig `json:"audio,omitempty"` + OutputModalities []string `json:"output_modalities,omitempty"` + Store *bool `json:"store,omitempty"` + Tools []map[string]any `json:"tools,omitempty"` + Avatar map[string]any `json:"avatar,omitempty"` + Greeting map[string]any `json:"greeting,omitempty"` + Handoff map[string]any `json:"handoff,omitempty"` + ToolChoice any `json:"tool_choice,omitempty"` + ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` + MaxOutputTokens any `json:"max_output_tokens,omitempty"` + Include []string `json:"include,omitempty"` } // VoiceAgentDefinitionFlat is the voice definition shape aligned with the @@ -437,12 +473,21 @@ type VoiceAgentDefinition struct { // provider details are sibling fields. type VoiceAgentDefinitionFlat struct { AgentDefinition - ModelType VoiceModelType `json:"model_type"` - Model string `json:"model"` - Instructions string `json:"instructions,omitempty"` - Audio *VoiceAudioConfigFlat `json:"audio,omitempty"` - OutputModalities []string `json:"output_modalities,omitempty"` - Store *bool `json:"store,omitempty"` + ModelType VoiceModelType `json:"model_type"` + Model string `json:"model"` + Instructions string `json:"instructions,omitempty"` + StructuredInputs map[string]any `json:"structured_inputs,omitempty"` + Audio *VoiceAudioConfigFlat `json:"audio,omitempty"` + OutputModalities []string `json:"output_modalities,omitempty"` + Store *bool `json:"store,omitempty"` + Tools []map[string]any `json:"tools,omitempty"` + Avatar map[string]any `json:"avatar,omitempty"` + Greeting map[string]any `json:"greeting,omitempty"` + Handoff map[string]any `json:"handoff,omitempty"` + ToolChoice any `json:"tool_choice,omitempty"` + ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` + MaxOutputTokens any `json:"max_output_tokens,omitempty"` + Include []string `json:"include,omitempty"` } // CreateAgentVersionRequest represents a request to create an agent version diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go index b2c9ae5cb9d..516d93aac96 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map.go @@ -593,10 +593,22 @@ func flatVoiceType(voice *agent_api.VoiceConfig) string { return voice.Type } +func normalizeFlatVoiceType(voiceType string) string { + switch strings.TrimSpace(voiceType) { + case "azure_standard": + return "azure-standard" + default: + return strings.TrimSpace(voiceType) + } +} + func flatVoiceLocale(voice *agent_api.VoiceConfig) string { if voice == nil || voice.Name == "" || isOpenAIVoice(voice.Name) { return "" } + if voice.Locale != nil && strings.TrimSpace(*voice.Locale) != "" { + return strings.TrimSpace(*voice.Locale) + } parts := strings.SplitN(voice.Name, "-", 3) if len(parts) < 2 { return "" @@ -604,6 +616,114 @@ func flatVoiceLocale(voice *agent_api.VoiceConfig) string { return parts[0] + "-" + parts[1] } +func defaultVoiceAudioFormat() *agent_api.VoiceAudioFormat { + rate := defaultVoiceAudioRate + return &agent_api.VoiceAudioFormat{Type: defaultVoiceAudioType, Rate: &rate} +} + +func mapVoiceAudioFormat(format *VoiceAudioFormat, fallback *agent_api.VoiceAudioFormat) *agent_api.VoiceAudioFormat { + out := &agent_api.VoiceAudioFormat{} + if fallback != nil { + *out = *fallback + } + if format != nil { + if strings.TrimSpace(format.Type) != "" { + out.Type = strings.TrimSpace(format.Type) + } + if format.Rate != nil { + out.Rate = format.Rate + } + } + return out +} + +func mapVoiceTurnDetection(turnDetection *VoiceTurnDetection) *agent_api.VoiceTurnDetection { + out := &agent_api.VoiceTurnDetection{Type: defaultVoiceTurnDetectionType} + if turnDetection == nil { + return out + } + if strings.TrimSpace(turnDetection.Type) != "" { + out.Type = strings.TrimSpace(turnDetection.Type) + } + out.Threshold = turnDetection.Threshold + out.PrefixPaddingMs = turnDetection.PrefixPaddingMs + out.SilenceDurationMs = turnDetection.SilenceDurationMs + out.CreateResponse = turnDetection.CreateResponse + out.Eagerness = turnDetection.Eagerness + out.SpeechDurationMs = turnDetection.SpeechDurationMs + out.RemoveFillerWords = turnDetection.RemoveFillerWords + out.InterruptResponse = turnDetection.InterruptResponse + out.Languages = turnDetection.Languages + out.AutoTruncate = turnDetection.AutoTruncate + return out +} + +func mapVoiceTranscription(transcription *VoiceTranscription) *agent_api.VoiceTranscription { + out := &agent_api.VoiceTranscription{Model: defaultVoiceInputTranscriptionModel} + if transcription == nil { + return out + } + if strings.TrimSpace(transcription.Model) != "" { + out.Model = strings.TrimSpace(transcription.Model) + } + out.Language = transcription.Language + out.Prompt = transcription.Prompt + return out +} + +func mapVoiceConfig(voice *VoiceConfig, fallbackName string) *agent_api.VoiceConfig { + if voice == nil { + return buildVoiceConfig(fallbackName) + } + name := strings.TrimSpace(voice.Name) + if name == "" { + name = fallbackName + } + voiceType := strings.TrimSpace(voice.Type) + if voiceType == "" { + out := buildVoiceConfig(name) + out.Style = voice.Style + out.Pitch = voice.Pitch + out.Rate = voice.Rate + out.Locale = voice.Locale + out.Volume = voice.Volume + return out + } + return &agent_api.VoiceConfig{ + Type: voiceType, + Name: name, + Style: voice.Style, + Pitch: voice.Pitch, + Rate: voice.Rate, + Locale: voice.Locale, + Volume: voice.Volume, + } +} + +func mapVoiceStructuredInputs(inputs map[string]any) map[string]any { + if len(inputs) == 0 { + return nil + } + out := make(map[string]any, len(inputs)) + for name, input := range inputs { + inputMap, ok := input.(map[string]any) + if !ok { + out[name] = input + continue + } + + mapped := maps.Clone(inputMap) + if value, ok := mapped["defaultValue"]; ok { + if _, hasSnakeCase := mapped["default_value"]; !hasSnakeCase { + mapped["default_value"] = value + } + delete(mapped, "defaultValue") + } + out[name] = mapped + } + return out +} + // CreateVoiceAgentAPIRequest builds a CreateAgentRequest for a declarative // voice agent. It translates the authoring kind "prompt-voice" into the // data-plane service kind "voice" and defaults the audio pipeline. @@ -648,36 +768,76 @@ func createVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRe voiceName = *voiceAgent.Voice } - audioFormat := &agent_api.VoiceAudioFormat{ - Type: defaultVoiceAudioType, - Rate: defaultVoiceAudioRate, + inputFormat := defaultVoiceAudioFormat() + outputFormat := defaultVoiceAudioFormat() + turnDetection := mapVoiceTurnDetection(nil) + transcription := mapVoiceTranscription(nil) + var noiseReduction *agent_api.VoiceNoiseReduction + var echoCancellation map[string]any + outputVoice := buildVoiceConfig(voiceName) + var outputSpeed *float64 + if voiceAgent.Audio != nil { + if voiceAgent.Audio.Input != nil { + inputFormat = mapVoiceAudioFormat(voiceAgent.Audio.Input.Format, inputFormat) + if voiceAgent.Audio.Input.NoiseReduction != nil { + noiseReduction = &agent_api.VoiceNoiseReduction{Type: strings.TrimSpace(voiceAgent.Audio.Input.NoiseReduction.Type)} + } + echoCancellation = voiceAgent.Audio.Input.EchoCancellation + turnDetection = mapVoiceTurnDetection(voiceAgent.Audio.Input.TurnDetection) + transcription = mapVoiceTranscription(voiceAgent.Audio.Input.Transcription) + } + if voiceAgent.Audio.Output != nil { + outputFormat = mapVoiceAudioFormat(voiceAgent.Audio.Output.Format, outputFormat) + outputVoice = mapVoiceConfig(voiceAgent.Audio.Output.Voice, voiceName) + outputSpeed = voiceAgent.Audio.Output.Speed + } + } + + outputModalities := []string{"audio"} + if len(voiceAgent.OutputModalities) > 0 { + outputModalities = voiceAgent.OutputModalities } input := &agent_api.VoiceInputConfig{ - Format: audioFormat, - TurnDetection: &agent_api.VoiceTurnDetection{Type: defaultVoiceTurnDetectionType}, - Transcription: &agent_api.VoiceTranscription{Model: defaultVoiceInputTranscriptionModel}, + Format: inputFormat, + NoiseReduction: noiseReduction, + EchoCancellation: echoCancellation, + TurnDetection: turnDetection, + Transcription: transcription, } - voiceConfig := buildVoiceConfig(voiceName) voiceDef := agent_api.VoiceAgentDefinitionFlat{ AgentDefinition: agent_api.AgentDefinition{ // Translate authoring kind prompt-voice -> service kind voice. Kind: agent_api.AgentKindVoice, }, - ModelType: modelType, - Model: modelID, - Instructions: instructions, + ModelType: modelType, + Model: modelID, + Instructions: instructions, + StructuredInputs: mapVoiceStructuredInputs(voiceAgent.StructuredInputs), Audio: &agent_api.VoiceAudioConfigFlat{ Input: input, Output: &agent_api.VoiceOutputConfigFlat{ - Format: audioFormat, - Voice: voiceConfig.Name, - VoiceType: flatVoiceType(voiceConfig), - VoiceLocale: flatVoiceLocale(voiceConfig), + Format: outputFormat, + Voice: outputVoice.Name, + VoiceType: normalizeFlatVoiceType(flatVoiceType(outputVoice)), + VoiceLocale: flatVoiceLocale(outputVoice), + Style: outputVoice.Style, + Pitch: outputVoice.Pitch, + Rate: outputVoice.Rate, + Volume: outputVoice.Volume, + Speed: outputSpeed, }, }, - OutputModalities: []string{"audio"}, - Store: voiceAgent.Store, + OutputModalities: outputModalities, + Store: voiceAgent.Store, + Tools: voiceAgent.Tools, + Avatar: voiceAgent.Avatar, + Greeting: voiceAgent.Greeting, + Handoff: voiceAgent.Handoff, + ToolChoice: voiceAgent.ToolChoice, + ParallelToolCalls: voiceAgent.ParallelToolCalls, + MaxOutputTokens: voiceAgent.MaxOutputTokens, + Include: voiceAgent.Include, } return createAgentAPIRequest(voiceAgent.AgentDefinition, voiceDef, nil, nil) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go index 4b6e78ae065..29c4e429fc6 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go @@ -10,6 +10,8 @@ import ( "azureaiagent/internal/pkg/agents/agent_api" ) +func ptr[T any](v T) *T { return &v } + // --------------------------------------------------------------------------- // isOpenAIVoice / buildVoiceConfig // --------------------------------------------------------------------------- @@ -118,7 +120,8 @@ func TestCreateVoiceAgentAPIRequest_Defaults(t *testing.T) { t.Fatalf("Audio pipeline not populated: %+v", def.Audio) } in := def.Audio.Input - if in.Format == nil || in.Format.Type != defaultVoiceAudioType || in.Format.Rate != defaultVoiceAudioRate { + if in.Format == nil || in.Format.Type != defaultVoiceAudioType || in.Format.Rate == nil || + *in.Format.Rate != defaultVoiceAudioRate { t.Errorf("input format = %+v", in.Format) } if in.TurnDetection == nil || in.TurnDetection.Type != defaultVoiceTurnDetectionType { @@ -128,7 +131,8 @@ func TestCreateVoiceAgentAPIRequest_Defaults(t *testing.T) { t.Errorf("transcription = %+v", in.Transcription) } out := def.Audio.Output - if out.Format == nil || out.Format.Type != defaultVoiceAudioType || out.Format.Rate != defaultVoiceAudioRate { + if out.Format == nil || out.Format.Type != defaultVoiceAudioType || out.Format.Rate == nil || + *out.Format.Rate != defaultVoiceAudioRate { t.Errorf("output format = %+v", out.Format) } // Default voice is the DragonHD Azure Neural voice in the flat unified shape. @@ -263,6 +267,100 @@ func TestCreateVoiceAgentAPIRequestFlat_MarshalWireShape(t *testing.T) { } } +func TestCreateVoiceAgentAPIRequestFlat_AdvancedSettingsWireShape(t *testing.T) { + t.Parallel() + inRate := 16000 + outRate := 24000 + threshold := 0.6 + speechDurationMs := 120 + createResponse := true + removeFillerWords := true + interruptResponse := true + autoTruncate := true + speed := 1.1 + parallelToolCalls := true + style := "cheerful" + pitch := "+0Hz" + rate := "+0%" + volume := "+0%" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-advanced"}, + Model: &Model{Id: "gpt-realtime"}, + Instructions: ptr("You are {{persona}}, a concise voice assistant."), + StructuredInputs: map[string]any{ + "persona": map[string]any{"description": "Assistant persona", "defaultValue": "Ada"}, + }, + Audio: &VoiceAudio{ + Input: &VoiceAudioInput{ + Format: &VoiceAudioFormat{Type: "audio/pcmu", Rate: &inRate}, + NoiseReduction: &VoiceNoiseReduction{Type: "near_field"}, + EchoCancellation: map[string]any{"type": "server_echo_cancellation", "channels": 1}, + TurnDetection: &VoiceTurnDetection{ + Type: "azure_semantic_vad", + Threshold: &threshold, + SpeechDurationMs: &speechDurationMs, + CreateResponse: &createResponse, + RemoveFillerWords: &removeFillerWords, + InterruptResponse: &interruptResponse, + Languages: []string{"en-US"}, + AutoTruncate: &autoTruncate, + }, + Transcription: &VoiceTranscription{Model: "whisper-1", Language: ptr("en-US"), Prompt: ptr("Contoso terms")}, + }, + Output: &VoiceAudioOutput{ + Format: &VoiceAudioFormat{Type: "audio/pcm", Rate: &outRate}, + Voice: &VoiceConfig{ + Type: "azure_standard", Name: "en-US-AvaNeural", Style: &style, + Pitch: &pitch, Rate: &rate, Locale: ptr("en-US"), Volume: &volume, + }, + Speed: &speed, + }, + }, + OutputModalities: []string{"audio", "text"}, + Tools: []map[string]any{{"type": "system", "name": "end_conversation"}}, + Avatar: map[string]any{"type": "video_avatar", "character": "lisa", "output_protocol": "webrtc"}, + Greeting: map[string]any{"type": "template", "text": "Hello {{persona}}"}, + ToolChoice: "auto", + ParallelToolCalls: ¶llelToolCalls, + MaxOutputTokens: "inf", + Include: []string{"item.input_audio_transcription.phrases"}, + } + + req, err := CreateVoiceAgentAPIRequestFlat(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + payload, err := json.Marshal(req) + if err != nil { + t.Fatalf("marshal request: %v", err) + } + + var wire map[string]any + if err := json.Unmarshal(payload, &wire); err != nil { + t.Fatalf("unmarshal payload: %v", err) + } + def := wire["definition"].(map[string]any) + input := def["audio"].(map[string]any)["input"].(map[string]any) + output := def["audio"].(map[string]any)["output"].(map[string]any) + structured := def["structured_inputs"].(map[string]any)["persona"].(map[string]any) + + if structured["default_value"] != "Ada" || structured["defaultValue"] != nil { + t.Fatalf("structured input default was not mapped to wire shape: %#v", structured) + } + if output["voice"] != "en-US-AvaNeural" || output["voice_type"] != "azure-standard" || output["style"] != style { + t.Fatalf("output voice flat shape not mapped: %#v", output) + } + if input["echo_cancellation"].(map[string]any)["type"] != "server_echo_cancellation" { + t.Fatalf("echo cancellation not mapped: %#v", input["echo_cancellation"]) + } + if def["tool_choice"] != "auto" || def["max_output_tokens"] != "inf" { + t.Fatalf("response options not mapped: %#v", def) + } + if len(def["tools"].([]any)) != 1 || def["avatar"].(map[string]any)["character"] != "lisa" { + t.Fatalf("tools/avatar not mapped: %#v", def) + } +} + // TestCreateVoiceAgentAPIRequest_ExplicitManaged verifies that explicitly // setting model_type: managed is accepted (idempotent with the default). func TestCreateVoiceAgentAPIRequest_ExplicitManaged(t *testing.T) { diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go index 996eae8a561..42e894667fc 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go @@ -460,6 +460,7 @@ func ValidateAgentDefinition(templateBytes []byte) error { "template.model_type '%s' is not supported; use '%s' or '%s'", agent.ModelType, VoiceModelTypeManaged, VoiceModelTypeSelfDeployed)) } + errors = append(errors, validateVoiceAgentAdvancedConfig(agent)...) } else { errors = append(errors, fmt.Sprintf("failed to unmarshal to VoiceAgent: %v", err)) } @@ -479,6 +480,74 @@ func ValidateAgentDefinition(templateBytes []byte) error { return nil } +func validateVoiceAgentAdvancedConfig(agent VoiceAgent) []string { + var errors []string + for i, modality := range agent.OutputModalities { + if strings.TrimSpace(modality) == "" { + errors = append(errors, fmt.Sprintf("template.output_modalities[%d] must not be blank", i)) + } + } + + if agent.Audio == nil { + return errors + } + if agent.Audio.Input != nil { + errors = append(errors, validateVoiceAudioFormat("template.audio.input.format", agent.Audio.Input.Format)...) + if nr := agent.Audio.Input.NoiseReduction; nr != nil && strings.TrimSpace(nr.Type) == "" { + errors = append(errors, "template.audio.input.noise_reduction.type must not be blank") + } + if td := agent.Audio.Input.TurnDetection; td != nil { + if strings.TrimSpace(td.Type) == "" { + errors = append(errors, "template.audio.input.turn_detection.type must not be blank") + } + if td.Threshold != nil && (*td.Threshold < 0 || *td.Threshold > 1) { + errors = append(errors, "template.audio.input.turn_detection.threshold must be between 0 and 1") + } + if td.PrefixPaddingMs != nil && *td.PrefixPaddingMs < 0 { + errors = append(errors, "template.audio.input.turn_detection.prefix_padding_ms must be >= 0") + } + if td.SilenceDurationMs != nil && *td.SilenceDurationMs < 0 { + errors = append(errors, "template.audio.input.turn_detection.silence_duration_ms must be >= 0") + } + if td.SpeechDurationMs != nil && *td.SpeechDurationMs < 0 { + errors = append(errors, "template.audio.input.turn_detection.speech_duration_ms must be >= 0") + } + } + } + if agent.Audio.Output != nil { + errors = append(errors, validateVoiceAudioFormat("template.audio.output.format", agent.Audio.Output.Format)...) + if voice := agent.Audio.Output.Voice; voice != nil { + if strings.TrimSpace(voice.Type) == "" { + errors = append(errors, "template.audio.output.voice.type must not be blank") + } + if strings.TrimSpace(voice.Name) == "" { + errors = append(errors, "template.audio.output.voice.name must not be blank") + } + } + if speed := agent.Audio.Output.Speed; speed != nil && (*speed < 0.25 || *speed > 1.5) { + errors = append(errors, "template.audio.output.speed must be between 0.25 and 1.5") + } + } + return errors +} + +func validateVoiceAudioFormat(path string, format *VoiceAudioFormat) []string { + if format == nil { + return nil + } + var errors []string + formatType := strings.TrimSpace(format.Type) + if formatType == "" { + errors = append(errors, path+".type must not be blank") + } else if formatType != "audio/pcm" && formatType != "audio/pcmu" && formatType != "audio/pcma" { + errors = append(errors, path+".type must be 'audio/pcm', 'audio/pcmu', or 'audio/pcma'") + } + if format.Rate != nil && *format.Rate <= 0 { + errors = append(errors, path+".rate must be greater than 0") + } + return errors +} + // Validate that the agent name matches the expected deployable format func ValidateAgentName(name string) error { if name == "" { diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/yaml.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/yaml.go index 46fffca9e6a..ffa35d057db 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/yaml.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/yaml.go @@ -214,9 +214,98 @@ type VoiceAgent struct { // Voice is the output voice name (e.g. "en-US-Ava:DragonHDLatestNeural" for // an Azure Neural voice, or "alloy" for an OpenAI realtime voice). Voice *string `json:"voice,omitempty" yaml:"voice,omitempty"` + // StructuredInputs declares template inputs used by voice instructions and greeting. + StructuredInputs map[string]any `json:"structuredInputs,omitempty" yaml:"structured_inputs,omitempty"` + // Audio customizes the input and output voice pipeline. Missing fields keep azd defaults. + Audio *VoiceAudio `json:"audio,omitempty" yaml:"audio,omitempty"` + // OutputModalities declares response modalities such as audio, text, animation, or avatar. + OutputModalities []string `json:"outputModalities,omitempty" yaml:"output_modalities,omitempty"` // Store toggles server-side logging (transcript + per-turn audio). Optional; // the service defaults to false when omitted. Store *bool `json:"store,omitempty" yaml:"store,omitempty"` + // Tools are passed through to the prompt voice service. Supported direct tool + // types include function, mcp, system, and toolbox. + Tools []map[string]any `json:"tools,omitempty" yaml:"tools,omitempty"` + // Avatar customizes voice avatar output for services that support it. + Avatar map[string]any `json:"avatar,omitempty" yaml:"avatar,omitempty"` + // Greeting configures initial greeting behavior for services that support it. + Greeting map[string]any `json:"greeting,omitempty" yaml:"greeting,omitempty"` + // Handoff configures voice handoff behavior for services that support it. + Handoff map[string]any `json:"handoff,omitempty" yaml:"handoff,omitempty"` + // ToolChoice configures service tool choice behavior, such as auto/none/required. + ToolChoice any `json:"toolChoice,omitempty" yaml:"tool_choice,omitempty"` + // ParallelToolCalls toggles parallel tool calls. + ParallelToolCalls *bool `json:"parallelToolCalls,omitempty" yaml:"parallel_tool_calls,omitempty"` + // MaxOutputTokens limits response output tokens. Use an integer or service-supported string such as "inf". + MaxOutputTokens any `json:"maxOutputTokens,omitempty" yaml:"max_output_tokens,omitempty"` + // Include requests additional service response fields. + Include []string `json:"include,omitempty" yaml:"include,omitempty"` +} + +// VoiceAudio bundles optional prompt voice input/output audio overrides. +type VoiceAudio struct { + Input *VoiceAudioInput `json:"input,omitempty" yaml:"input,omitempty"` + Output *VoiceAudioOutput `json:"output,omitempty" yaml:"output,omitempty"` +} + +// VoiceAudioInput customizes caller-to-agent audio. +type VoiceAudioInput struct { + Format *VoiceAudioFormat `json:"format,omitempty" yaml:"format,omitempty"` + NoiseReduction *VoiceNoiseReduction `json:"noiseReduction,omitempty" yaml:"noise_reduction,omitempty"` + EchoCancellation map[string]any `json:"echoCancellation,omitempty" yaml:"echo_cancellation,omitempty"` + TurnDetection *VoiceTurnDetection `json:"turnDetection,omitempty" yaml:"turn_detection,omitempty"` + Transcription *VoiceTranscription `json:"transcription,omitempty" yaml:"transcription,omitempty"` +} + +// VoiceAudioOutput customizes agent-to-caller audio. +type VoiceAudioOutput struct { + Format *VoiceAudioFormat `json:"format,omitempty" yaml:"format,omitempty"` + Voice *VoiceConfig `json:"voice,omitempty" yaml:"voice,omitempty"` + Speed *float64 `json:"speed,omitempty" yaml:"speed,omitempty"` +} + +// VoiceAudioFormat describes an audio stream format. +type VoiceAudioFormat struct { + Type string `json:"type" yaml:"type"` + Rate *int `json:"rate,omitempty" yaml:"rate,omitempty"` +} + +// VoiceNoiseReduction configures input audio noise reduction. +type VoiceNoiseReduction struct { + Type string `json:"type" yaml:"type"` +} + +// VoiceTurnDetection configures server-side turn detection. +type VoiceTurnDetection struct { + Type string `json:"type" yaml:"type"` + Threshold *float64 `json:"threshold,omitempty" yaml:"threshold,omitempty"` + PrefixPaddingMs *int `json:"prefixPaddingMs,omitempty" yaml:"prefix_padding_ms,omitempty"` + SilenceDurationMs *int `json:"silenceDurationMs,omitempty" yaml:"silence_duration_ms,omitempty"` + CreateResponse *bool `json:"createResponse,omitempty" yaml:"create_response,omitempty"` + Eagerness *string `json:"eagerness,omitempty" yaml:"eagerness,omitempty"` + SpeechDurationMs *int `json:"speechDurationMs,omitempty" yaml:"speech_duration_ms,omitempty"` + RemoveFillerWords *bool `json:"removeFillerWords,omitempty" yaml:"remove_filler_words,omitempty"` + InterruptResponse *bool `json:"interruptResponse,omitempty" yaml:"interrupt_response,omitempty"` + Languages []string `json:"languages,omitempty" yaml:"languages,omitempty"` + AutoTruncate *bool `json:"autoTruncate,omitempty" yaml:"auto_truncate,omitempty"` +} + +// VoiceTranscription configures input transcription. +type VoiceTranscription struct { + Model string `json:"model,omitempty" yaml:"model,omitempty"` + Language *string `json:"language,omitempty" yaml:"language,omitempty"` + Prompt *string `json:"prompt,omitempty" yaml:"prompt,omitempty"` +} + +// VoiceConfig selects the output voice. +type VoiceConfig struct { + Type string `json:"type" yaml:"type"` + Name string `json:"name" yaml:"name"` + Style *string `json:"style,omitempty" yaml:"style,omitempty"` + Pitch *string `json:"pitch,omitempty" yaml:"pitch,omitempty"` + Rate *string `json:"rate,omitempty" yaml:"rate,omitempty"` + Locale *string `json:"locale,omitempty" yaml:"locale,omitempty"` + Volume *string `json:"volume,omitempty" yaml:"volume,omitempty"` } // ContainerResources represents the resource allocation for a containerized agent. diff --git a/cli/azd/extensions/azure.ai.agents/internal/project/agent_definition.go b/cli/azd/extensions/azure.ai.agents/internal/project/agent_definition.go index 26b5a06f874..1625d9a7637 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/project/agent_definition.go +++ b/cli/azd/extensions/azure.ai.agents/internal/project/agent_definition.go @@ -138,35 +138,68 @@ type AgentDefinitionInline struct { // Voice-agent fields (kind: prompt-voice). All omitempty so container/ // workflow entries are byte-for-byte unchanged. - ModelType agent_yaml.VoiceModelType `json:"modelType,omitempty"` - Model *agent_yaml.Model `json:"model,omitempty"` - Instructions *string `json:"instructions,omitempty"` - Voice *string `json:"voice,omitempty"` - Store *bool `json:"store,omitempty"` + ModelType agent_yaml.VoiceModelType `json:"modelType,omitempty"` + Model *agent_yaml.Model `json:"model,omitempty"` + Instructions *string `json:"instructions,omitempty"` + Voice *string `json:"voice,omitempty"` + StructuredInputs map[string]any `json:"structuredInputs,omitempty"` + Audio *agent_yaml.VoiceAudio `json:"audio,omitempty"` + OutputModalities []string `json:"outputModalities,omitempty"` + Store *bool `json:"store,omitempty"` + Tools []map[string]any `json:"tools,omitempty"` + Avatar map[string]any `json:"avatar,omitempty"` + Greeting map[string]any `json:"greeting,omitempty"` + Handoff map[string]any `json:"handoff,omitempty"` + ToolChoice any `json:"toolChoice,omitempty"` + ParallelToolCalls *bool `json:"parallelToolCalls,omitempty"` + MaxOutputTokens any `json:"maxOutputTokens,omitempty"` + Include []string `json:"include,omitempty"` } // voiceAgentDefinitionToInline projects a VoiceAgent into the inline definition // written to azure.yaml. Voice agents carry no container/image/code config. func voiceAgentDefinitionToInline(va agent_yaml.VoiceAgent) AgentDefinitionInline { return AgentDefinitionInline{ - AgentDefinition: va.AgentDefinition, - ModelType: va.ModelType, - Model: va.Model, - Instructions: va.Instructions, - Voice: va.Voice, - Store: va.Store, + AgentDefinition: va.AgentDefinition, + ModelType: va.ModelType, + Model: va.Model, + Instructions: va.Instructions, + Voice: va.Voice, + StructuredInputs: va.StructuredInputs, + Audio: va.Audio, + OutputModalities: va.OutputModalities, + Store: va.Store, + Tools: va.Tools, + Avatar: va.Avatar, + Greeting: va.Greeting, + Handoff: va.Handoff, + ToolChoice: va.ToolChoice, + ParallelToolCalls: va.ParallelToolCalls, + MaxOutputTokens: va.MaxOutputTokens, + Include: va.Include, } } // toVoiceAgent rebuilds an agent_yaml.VoiceAgent from the inline definition. func (d AgentDefinitionInline) toVoiceAgent() agent_yaml.VoiceAgent { return agent_yaml.VoiceAgent{ - AgentDefinition: d.AgentDefinition, - ModelType: d.ModelType, - Model: d.Model, - Instructions: d.Instructions, - Voice: d.Voice, - Store: d.Store, + AgentDefinition: d.AgentDefinition, + ModelType: d.ModelType, + Model: d.Model, + Instructions: d.Instructions, + Voice: d.Voice, + StructuredInputs: d.StructuredInputs, + Audio: d.Audio, + OutputModalities: d.OutputModalities, + Store: d.Store, + Tools: d.Tools, + Avatar: d.Avatar, + Greeting: d.Greeting, + Handoff: d.Handoff, + ToolChoice: d.ToolChoice, + ParallelToolCalls: d.ParallelToolCalls, + MaxOutputTokens: d.MaxOutputTokens, + Include: d.Include, } } diff --git a/cli/azd/extensions/azure.ai.agents/schemas/azure.ai.agent.json b/cli/azd/extensions/azure.ai.agents/schemas/azure.ai.agent.json index 55a8ea2c55d..6eca9a0ef5a 100644 --- a/cli/azd/extensions/azure.ai.agents/schemas/azure.ai.agent.json +++ b/cli/azd/extensions/azure.ai.agents/schemas/azure.ai.agent.json @@ -64,14 +64,62 @@ "type": "string", "description": "Voice agent (kind: prompt-voice) system prompt for the assistant." }, - "voice": { - "type": "string", - "description": "Voice agent (kind: prompt-voice) output voice name (e.g. 'en-US-Ava:DragonHDLatestNeural' for an Azure Neural voice, or 'alloy' for an OpenAI realtime voice)." - }, - "store": { - "type": "boolean", - "description": "Voice agent (kind: prompt-voice) server-side logging toggle (transcript + per-turn audio). Defaults to false when omitted." - }, + "voice": { + "type": "string", + "description": "Voice agent (kind: prompt-voice) output voice name (e.g. 'en-US-Ava:DragonHDLatestNeural' for an Azure Neural voice, or 'alloy' for an OpenAI realtime voice)." + }, + "structuredInputs": { + "type": "object", + "description": "Voice agent (kind: prompt-voice) structured prompt inputs. Use description, defaultValue, schema, and required; azd maps defaultValue to the service wire field default_value.", + "additionalProperties": true + }, + "audio": { + "$ref": "#/definitions/VoiceAudio" + }, + "outputModalities": { + "type": "array", + "description": "Voice agent (kind: prompt-voice) output modalities. Well-known values are audio, text, animation, and avatar.", + "items": { "type": "string", "minLength": 1 } + }, + "store": { + "type": "boolean", + "description": "Voice agent (kind: prompt-voice) server-side logging toggle (transcript + per-turn audio). Defaults to false when omitted." + }, + "tools": { + "type": "array", + "description": "Voice agent (kind: prompt-voice) tools. Direct tool types include function, mcp, system, and toolbox.", + "items": { "type": "object", "additionalProperties": true } + }, + "avatar": { + "type": "object", + "description": "Voice agent (kind: prompt-voice) avatar configuration.", + "additionalProperties": true + }, + "greeting": { + "type": "object", + "description": "Voice agent (kind: prompt-voice) greeting configuration, such as template or llm_generated.", + "additionalProperties": true + }, + "handoff": { + "type": "object", + "description": "Voice agent (kind: prompt-voice) handoff configuration.", + "additionalProperties": true + }, + "toolChoice": { + "description": "Voice agent (kind: prompt-voice) tool choice behavior, such as none, auto, required, or a tool choice object." + }, + "parallelToolCalls": { + "type": "boolean", + "description": "Voice agent (kind: prompt-voice) parallel tool call toggle." + }, + "maxOutputTokens": { + "description": "Voice agent (kind: prompt-voice) maximum output tokens. Use an integer or a service-supported string such as inf." + }, + "include": { + "type": "array", + "description": "Voice agent (kind: prompt-voice) extra service response fields to include.", + "items": { "type": "string" } + }, "name": { "type": "string", "description": "The agent name." @@ -152,7 +200,7 @@ "required": ["protocol"], "additionalProperties": false }, - "CodeConfiguration": { + "CodeConfiguration": { "type": "object", "description": "Code deploy configuration. When present, the agent is deployed from source (ZIP) instead of a container image.", "properties": { @@ -161,9 +209,96 @@ "dependencyResolution": { "type": "string", "description": "Dependency resolution mode (e.g., 'bundled', 'remote_build')." } }, "required": ["runtime", "entryPoint"], - "additionalProperties": false - }, - "SessionConfiguration": { + "additionalProperties": false + }, + "VoiceAudio": { + "type": "object", + "description": "Prompt voice input and output audio configuration. Requires AZURE_VOICE_AGENT_API=unified-flat for deployment.", + "properties": { + "input": { "$ref": "#/definitions/VoiceAudioInput" }, + "output": { "$ref": "#/definitions/VoiceAudioOutput" } + }, + "additionalProperties": false + }, + "VoiceAudioInput": { + "type": "object", + "properties": { + "format": { "$ref": "#/definitions/VoiceAudioFormat" }, + "noiseReduction": { "$ref": "#/definitions/VoiceNoiseReduction" }, + "echoCancellation": { "type": "object", "additionalProperties": true }, + "turnDetection": { "$ref": "#/definitions/VoiceTurnDetection" }, + "transcription": { "$ref": "#/definitions/VoiceTranscription" } + }, + "additionalProperties": false + }, + "VoiceAudioOutput": { + "type": "object", + "properties": { + "format": { "$ref": "#/definitions/VoiceAudioFormat" }, + "voice": { "$ref": "#/definitions/VoiceConfig" }, + "speed": { "type": "number", "minimum": 0.25, "maximum": 1.5 } + }, + "additionalProperties": false + }, + "VoiceAudioFormat": { + "type": "object", + "properties": { + "type": { "type": "string", "enum": ["audio/pcm", "audio/pcmu", "audio/pcma"] }, + "rate": { "type": "integer", "minimum": 1 } + }, + "required": ["type"], + "additionalProperties": false + }, + "VoiceNoiseReduction": { + "type": "object", + "properties": { + "type": { "type": "string", "description": "Well-known values include near_field, far_field, and azure_deep_noise_suppression." } + }, + "required": ["type"], + "additionalProperties": false + }, + "VoiceTurnDetection": { + "type": "object", + "properties": { + "type": { "type": "string", "description": "Well-known values include server_vad, semantic_vad, and azure_semantic_vad." }, + "threshold": { "type": "number", "minimum": 0, "maximum": 1 }, + "prefixPaddingMs": { "type": "integer", "minimum": 0 }, + "silenceDurationMs": { "type": "integer", "minimum": 0 }, + "createResponse": { "type": "boolean" }, + "eagerness": { "type": "string" }, + "speechDurationMs": { "type": "integer", "minimum": 0 }, + "removeFillerWords": { "type": "boolean" }, + "interruptResponse": { "type": "boolean" }, + "languages": { "type": "array", "items": { "type": "string" } }, + "autoTruncate": { "type": "boolean" } + }, + "required": ["type"], + "additionalProperties": false + }, + "VoiceTranscription": { + "type": "object", + "properties": { + "model": { "type": "string" }, + "language": { "type": "string" }, + "prompt": { "type": "string" } + }, + "additionalProperties": false + }, + "VoiceConfig": { + "type": "object", + "properties": { + "type": { "type": "string", "description": "Voice provider type, such as openai, azure_standard, or azure-standard." }, + "name": { "type": "string" }, + "style": { "type": "string" }, + "pitch": { "type": "string" }, + "rate": { "type": "string" }, + "locale": { "type": "string" }, + "volume": { "type": "string" } + }, + "required": ["type", "name"], + "additionalProperties": false + }, + "SessionConfiguration": { "type": "object", "description": "Optional hosted-agent session runtime settings. When omitted, the service applies its defaults (idle timeout 900 seconds).", "properties": { From 93fc6080554bb1ebe56700f5a5424f7d6ac8e365 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Thu, 20 Aug 2026 16:03:51 +0800 Subject: [PATCH 12/14] test(agents): avoid go fix pointer helper --- .../internal/pkg/agents/agent_yaml/map_voice_test.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go index 29c4e429fc6..425eeddb06c 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/map_voice_test.go @@ -10,8 +10,6 @@ import ( "azureaiagent/internal/pkg/agents/agent_api" ) -func ptr[T any](v T) *T { return &v } - // --------------------------------------------------------------------------- // isOpenAIVoice / buildVoiceConfig // --------------------------------------------------------------------------- @@ -283,10 +281,13 @@ func TestCreateVoiceAgentAPIRequestFlat_AdvancedSettingsWireShape(t *testing.T) pitch := "+0Hz" rate := "+0%" volume := "+0%" + instructions := "You are {{persona}}, a concise voice assistant." + language := "en-US" + prompt := "Contoso terms" agent := VoiceAgent{ AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-advanced"}, Model: &Model{Id: "gpt-realtime"}, - Instructions: ptr("You are {{persona}}, a concise voice assistant."), + Instructions: &instructions, StructuredInputs: map[string]any{ "persona": map[string]any{"description": "Assistant persona", "defaultValue": "Ada"}, }, @@ -305,13 +306,13 @@ func TestCreateVoiceAgentAPIRequestFlat_AdvancedSettingsWireShape(t *testing.T) Languages: []string{"en-US"}, AutoTruncate: &autoTruncate, }, - Transcription: &VoiceTranscription{Model: "whisper-1", Language: ptr("en-US"), Prompt: ptr("Contoso terms")}, + Transcription: &VoiceTranscription{Model: "whisper-1", Language: &language, Prompt: &prompt}, }, Output: &VoiceAudioOutput{ Format: &VoiceAudioFormat{Type: "audio/pcm", Rate: &outRate}, Voice: &VoiceConfig{ Type: "azure_standard", Name: "en-US-AvaNeural", Style: &style, - Pitch: &pitch, Rate: &rate, Locale: ptr("en-US"), Volume: &volume, + Pitch: &pitch, Rate: &rate, Locale: &language, Volume: &volume, }, Speed: &speed, }, From 25c10d27c28130f3ed6265acec47ead22f4cad80 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Fri, 21 Aug 2026 18:57:19 +0800 Subject: [PATCH 13/14] fix(agents): validate voice transcription includes --- .../internal/pkg/agents/agent_yaml/parse.go | 24 +++++++++++++++++-- .../pkg/agents/agent_yaml/parse_voice_test.go | 21 ++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go index 42e894667fc..a90fbe6046d 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse.go @@ -489,8 +489,9 @@ func validateVoiceAgentAdvancedConfig(agent VoiceAgent) []string { } if agent.Audio == nil { - return errors + return append(errors, validateVoiceIncludeTranscriptionCompatibility(agent, "")...) } + transcriptionModel := "" if agent.Audio.Input != nil { errors = append(errors, validateVoiceAudioFormat("template.audio.input.format", agent.Audio.Input.Format)...) if nr := agent.Audio.Input.NoiseReduction; nr != nil && strings.TrimSpace(nr.Type) == "" { @@ -513,6 +514,9 @@ func validateVoiceAgentAdvancedConfig(agent VoiceAgent) []string { errors = append(errors, "template.audio.input.turn_detection.speech_duration_ms must be >= 0") } } + if agent.Audio.Input.Transcription != nil { + transcriptionModel = agent.Audio.Input.Transcription.Model + } } if agent.Audio.Output != nil { errors = append(errors, validateVoiceAudioFormat("template.audio.output.format", agent.Audio.Output.Format)...) @@ -528,7 +532,23 @@ func validateVoiceAgentAdvancedConfig(agent VoiceAgent) []string { errors = append(errors, "template.audio.output.speed must be between 0.25 and 1.5") } } - return errors + return append(errors, validateVoiceIncludeTranscriptionCompatibility(agent, transcriptionModel)...) +} + +func validateVoiceIncludeTranscriptionCompatibility(agent VoiceAgent, transcriptionModel string) []string { + if !slices.Contains(agent.Include, "item.input_audio_transcription.phrases") { + return nil + } + model := strings.TrimSpace(transcriptionModel) + if model == "" { + model = defaultVoiceInputTranscriptionModel + } + if model == "azure-speech" || model == "azure-fast-transcription" { + return nil + } + return []string{ + "template.include item.input_audio_transcription.phrases requires template.audio.input.transcription.model to be azure-speech or azure-fast-transcription", + } } func validateVoiceAudioFormat(path string, format *VoiceAudioFormat) []string { diff --git a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse_voice_test.go index 6aba8a368dd..b348d867651 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse_voice_test.go +++ b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse_voice_test.go @@ -118,3 +118,24 @@ model_type: unsupported t.Fatalf("expected invalid model_type error, got: %v", err) } } +func TestValidateAgentDefinition_PromptVoice_InvalidIncludeTranscriptionModel(t *testing.T) { + yamlContent := []byte(` +kind: prompt-voice +name: voice-agent +model: + id: gpt-realtime +audio: + input: + transcription: + model: whisper-1 +include: + - item.input_audio_transcription.phrases +`) + err := ValidateAgentDefinition(yamlContent) + if err == nil { + t.Fatal("expected include/transcription validation error") + } + if !strings.Contains(err.Error(), "azure-speech") || !strings.Contains(err.Error(), "azure-fast-transcription") { + t.Fatalf("expected transcription model guidance in error, got: %v", err) + } +} From 8d09cb866e4f4725625142e98f9da5330fd6c072 Mon Sep 17 00:00:00 2001 From: Jian Wu <223556219+Copilot@users.noreply.github.com> Date: Mon, 24 Aug 2026 20:22:29 +0800 Subject: [PATCH 14/14] docs(agents): keep advanced voice docs private --- cli/azd/extensions/azure.ai.agents/README.md | 92 -------------------- 1 file changed, 92 deletions(-) diff --git a/cli/azd/extensions/azure.ai.agents/README.md b/cli/azd/extensions/azure.ai.agents/README.md index 8dd303f82a6..4ddac596f9a 100644 --- a/cli/azd/extensions/azure.ai.agents/README.md +++ b/cli/azd/extensions/azure.ai.agents/README.md @@ -199,98 +199,6 @@ keys throughout this block (`invocations_moderation`, `response_mode`, `input_paths`, `stream_selectors`, `event_type`, and so on). The **values** (`non_streaming`, `streaming`, `both`, `json`, `text`) are the same in both. -## Prompt voice advanced configuration - -Advanced prompt voice settings are authored on the `azure.ai.agent` service in -`azure.yaml` and require the unified flat API mode: - -```bash -azd env set AZURE_VOICE_AGENT_API unified-flat -``` - -```yaml -services: - voice-agent: - host: azure.ai.agent - kind: prompt-voice - name: voice-agent - modelType: managed # or self_deployed for BYOM - model: - id: gpt-realtime - instructions: You are {{persona}}, a concise voice assistant. - structuredInputs: - persona: - description: Assistant persona - defaultValue: Ada - schema: - type: string - audio: - input: - format: - type: audio/pcmu - noiseReduction: - type: near_field - echoCancellation: - type: server_echo_cancellation - reference_source: server - channels: 1 - turnDetection: - type: azure_semantic_vad - threshold: 0.6 - speechDurationMs: 120 - removeFillerWords: true - createResponse: true - interruptResponse: true - languages: [en-US] - autoTruncate: true - transcription: - model: whisper-1 - language: en-US - output: - format: - type: audio/pcm - rate: 24000 - voice: - type: azure_standard - name: en-US-AvaNeural - locale: en-US - style: cheerful - speed: 1.0 - outputModalities: [audio, text] - tools: - - type: system - name: end_conversation - avatar: - type: video_avatar - character: lisa - style: casual-sitting - output_protocol: webrtc - greeting: - type: template - text: Hello {{persona}} - toolChoice: auto - parallelToolCalls: true - maxOutputTokens: inf - include: - - item.input_audio_transcription.phrases -``` - -Notes: - -- `voice`, `instructions`, and `store` remain supported for simple prompt voice - agents. Missing audio fields keep the existing azd defaults. -- `audio.output.voice` uses an author-friendly object shape; in `unified-flat` - mode azd maps it to the service flat fields `voice`, `voice_type`, - `voice_locale`, `style`, `pitch`, `rate`, and `volume`. -- `structuredInputs.defaultValue` maps to the service wire field - `default_value`. -- Direct voice tool types are `function`, `mcp`, `system`, and `toolbox`. - Server-side tools such as `web_search`, `azure_ai_search`, and `openapi` must - be packaged through a toolbox. -- `tools`, `avatar`, `greeting`, `handoff`, `toolChoice`, and - `echoCancellation` intentionally remain light pass-through blocks so azd does - not block new service-side additions. - ## Session idle timeout A hosted agent's runtime session sandbox is suspended by Foundry after a period