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/cmd/doctor/checks_agent_status.go b/cli/azd/extensions/azure.ai.agents/internal/cmd/doctor/checks_agent_status.go index cdffffe264d..1ee42a84765 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}`). 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 5ffe129eeb1..613f57a306d 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. Prompt 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 @@ -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. + // Prompt 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..345998fbb48 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 +// prompt voice agents set VERSION before ENDPOINT; in both cases ENDPOINT is +// the deploy completion marker. func TestIsDeployed_VoiceEndpointFallback(t *testing.T) { t.Parallel() @@ -758,8 +758,25 @@ func TestIsDeployed_VoiceEndpointFallback(t *testing.T) { 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"}, + 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 (prompt 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": "wss://x/agents/a/endpoint/protocols/voice?api-version=v1", + }, isVoice: true, want: true, }, diff --git a/cli/azd/extensions/azure.ai.agents/internal/exterrors/codes.go b/cli/azd/extensions/azure.ai.agents/internal/exterrors/codes.go index 477c65a5a67..a4837d7bea7 100644 --- a/cli/azd/extensions/azure.ai.agents/internal/exterrors/codes.go +++ b/cli/azd/extensions/azure.ai.agents/internal/exterrors/codes.go @@ -194,6 +194,7 @@ const ( OpContainerPackage = "container_package" OpContainerPublish = "container_publish" OpCreateAgent = "create_agent" + OpGetAgent = "get_agent" OpUpdateAgent = "update_agent" OpGetActivityBot = "get_activity_bot" OpEnsureActivityBot = "ensure_activity_bot" 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 549f9610f12..03750f4e94e 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" ) @@ -360,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 @@ -370,32 +369,62 @@ 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"` -} - -// VoiceOutputConfig is the output (agent -> caller) audio configuration. + 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 for the +// unified /agents voice API. The voice name is a string and provider details are +// sibling fields. type VoiceOutputConfig struct { - Format *VoiceAudioFormat `json:"format,omitempty"` - Voice *VoiceConfig `json:"voice,omitempty"` + Format *VoiceAudioFormat `json:"format,omitempty"` + 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. @@ -404,17 +433,25 @@ type VoiceAudioConfig struct { Output *VoiceOutputConfig `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 the data-plane definition body for a declarative +// prompt voice agent. Its Kind is always AgentKindVoice ("voice"). 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"` } // CreateAgentVersionRequest represents a request to create an agent version 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..6670f8dc455 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,74 @@ func (c *AgentClient) CreateVoiceAgent( return &agent, nil } +// GetVoiceAgent 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) GetVoiceAgent( + 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 +} + +// CreateVoiceAgent creates a voice agent through the unified /agents +// collection. Prompt voice deploys use this path by default. +func (c *AgentClient) CreateVoiceAgent( + 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) +} + +// UpdateVoiceAgent creates a new version for an existing voice agent +// through the unified /agents/{name} endpoint. +func (c *AgentClient) UpdateVoiceAgent( + 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..58e84f0a573 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,7 +919,7 @@ func TestDownloadAgentCode_ReturnsErrorOnNon200(t *testing.T) { require.Error(t, err) } -func TestCreateVoiceAgent_PostsToVoiceCollectionWithPreviewHeader(t *testing.T) { +func TestCreateVoiceAgent_PostsToAgentsWithPreviewHeader(t *testing.T) { body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{}}}` client, transport := newCaptureClient(http.StatusOK, body) @@ -932,53 +932,56 @@ func TestCreateVoiceAgent_PostsToVoiceCollectionWithPreviewHeader(t *testing.T) 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, "/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")) - // 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 TestCreateVoiceAgent_SetsOverriddenHostHeader(t *testing.T) { - client, transport := newCaptureClient(http.StatusCreated, `{"name":"my-voice","versions":{"latest":{}}}`) +func TestGetVoiceAgent_GetsNamedAgentWithPreviewHeader(t *testing.T) { + body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{"version":"3"}}}` + client, transport := newCaptureClient(http.StatusOK, body) - _, err := client.CreateVoiceAgent( + agent, err := client.GetVoiceAgent( t.Context(), - &CreateAgentRequest{Name: "my-voice"}, + "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) - require.Equal( - t, - "regional.hyena.example.com", - transport.requests[0].Header.Get("x-ms-overridden-host"), - ) + 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 TestCreateVoiceAgent_ReturnsErrorOnNonSuccess(t *testing.T) { - client, _ := newCaptureClient( - http.StatusForbidden, - `{"error":{"code":"preview_feature_required","message":"voice agents preview"}}`, - ) +func TestUpdateVoiceAgent_PostsToNamedAgentWithPreviewHeader(t *testing.T) { + body := `{"object":"agent","id":"va-1","name":"my-voice","versions":{"latest":{"version":"2"}}}` + client, transport := newCaptureClient(http.StatusOK, body) - _, err := client.CreateVoiceAgent( + agent, err := client.UpdateVoiceAgent( t.Context(), - &CreateAgentRequest{Name: "my-voice"}, + "my-voice", + &UpdateAgentRequest{}, AgentEndpointAPIVersion, - "", + "regional.hyena.example.com", ) - require.Error(t, err) + 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")) } 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 ea3e42f2870..cc5549a588c 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 @@ -549,11 +549,11 @@ var knownOpenAIVoices = map[string]struct{}{ } // azureNeuralVoicePattern matches the locale prefix that every Azure Neural -// voice name carries, e.g. "en-US-Ava:DragonHDLatestNeural" or -// "ja-JP-NanamiNeural". The service contract guarantees this -- -// shape for Azure voices, which is what distinguishes them from the flat -// lowercase OpenAI voice tokens. -var azureNeuralVoicePattern = regexp.MustCompile(`^[a-z]{2,3}-[A-Z]{2,3}-`) +// voice name carries, e.g. "en-US-Ava:DragonHDLatestNeural", +// "ja-JP-NanamiNeural", or Azure voices with script/numeric-region locales. +// The optional script tag and numeric region support keep valid BCP-47 locales +// from being classified as OpenAI voices. +var azureNeuralVoicePattern = regexp.MustCompile(`^([a-z]{2,3}(?:-[A-Z][a-z]{3})?-(?:[A-Z]{2,3}|[0-9]{3}))-`) // isOpenAIVoice reports whether a voice name denotes an OpenAI realtime voice // (e.g. "alloy") vs an Azure Neural voice (e.g. "en-US-Ava:DragonHDLatestNeural"). @@ -583,10 +583,143 @@ func buildVoiceConfig(name string) *agent_api.VoiceConfig { return &agent_api.VoiceConfig{Type: "azure_standard", Name: trimmed} } +func voiceWireType(voice *agent_api.VoiceConfig) string { + if voice == nil { + return "" + } + if voice.Type == "azure_standard" { + return "azure-standard" + } + return voice.Type +} + +func voiceWireLocale(voice *agent_api.VoiceConfig) string { + if voice == nil || voice.Name == "" || isOpenAIVoice(voice.Name) { + return "" + } + match := azureNeuralVoicePattern.FindStringSubmatch(voice.Name) + if len(match) < 2 { + return "" + } + return match[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. func CreateVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { + return createVoiceAgentAPIRequest(voiceAgent) +} + +func createVoiceAgentAPIRequest(voiceAgent VoiceAgent) (*agent_api.CreateAgentRequest, error) { modelID := "" if voiceAgent.Model != nil { modelID = strings.TrimSpace(voiceAgent.Model.Id) @@ -615,32 +748,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: inputFormat, + NoiseReduction: noiseReduction, + EchoCancellation: echoCancellation, + TurnDetection: turnDetection, + Transcription: transcription, + } voiceDef := agent_api.VoiceAgentDefinition{ 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.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), + Format: outputFormat, + Voice: outputVoice.Name, + VoiceType: voiceWireType(outputVoice), + VoiceLocale: voiceWireLocale(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 137e9b6e847..b507e68b377 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,11 +4,14 @@ package agent_yaml import ( + "encoding/json" "testing" "azureaiagent/internal/pkg/agents/agent_api" ) +func ptr[T any](v T) *T { return &v } + // --------------------------------------------------------------------------- // isOpenAIVoice / buildVoiceConfig // --------------------------------------------------------------------------- @@ -117,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 { @@ -127,12 +131,13 @@ 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. - 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 { @@ -164,7 +169,7 @@ func TestCreateVoiceAgentAPIRequest_Overrides(t *testing.T) { 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 { @@ -172,6 +177,236 @@ func TestCreateVoiceAgentAPIRequest_Overrides(t *testing.T) { } } +func TestCreateVoiceAgentAPIRequest_UsesServiceOutputShape(t *testing.T) { + t.Parallel() + voice := "alloy" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-agent"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &voice, + } + + req, err := CreateVoiceAgentAPIRequest(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + def := req.Definition.(agent_api.VoiceAgentDefinition) + 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 TestCreateVoiceAgentAPIRequest_UsesAzureVoiceLocale(t *testing.T) { + t.Parallel() + voice := "en-US-Ava:DragonHDLatestNeural" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-agent"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &voice, + } + + req, err := CreateVoiceAgentAPIRequest(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + def := req.Definition.(agent_api.VoiceAgentDefinition) + 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) + } +} + +func TestCreateVoiceAgentAPIRequest_UsesAzureVoiceLocaleVariants(t *testing.T) { + t.Parallel() + tests := []struct { + name string + voice string + wantLocale string + }{ + {name: "script locale", voice: "az-Latn-AZ-BanuNeural", wantLocale: "az-Latn-AZ"}, + {name: "numeric region", voice: "es-419-AnaNeural", wantLocale: "es-419"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-agent"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &tt.voice, + } + + req, err := CreateVoiceAgentAPIRequest(agent) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + def := req.Definition.(agent_api.VoiceAgentDefinition) + if def.Audio.Output.Voice != tt.voice { + t.Errorf("Voice = %q, want %q", def.Audio.Output.Voice, tt.voice) + } + if def.Audio.Output.VoiceType != "azure-standard" { + t.Errorf("VoiceType = %q, want azure-standard", def.Audio.Output.VoiceType) + } + if def.Audio.Output.VoiceLocale != tt.wantLocale { + t.Errorf("VoiceLocale = %q, want %q", def.Audio.Output.VoiceLocale, tt.wantLocale) + } + }) + } +} + +func TestCreateVoiceAgentAPIRequest_MarshalServiceWireShape(t *testing.T) { + t.Parallel() + voice := "en-US-Ava:DragonHDLatestNeural" + agent := VoiceAgent{ + AgentDefinition: AgentDefinition{Kind: AgentKindPromptVoice, Name: "voice-agent"}, + Model: &Model{Id: "gpt-realtime"}, + Voice: &voice, + } + + req, err := CreateVoiceAgentAPIRequest(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, ok := wire["definition"].(map[string]any) + if !ok { + t.Fatalf("definition = %#v, want object", wire["definition"]) + } + audio, ok := definition["audio"].(map[string]any) + if !ok { + t.Fatalf("definition.audio = %#v, want object", definition["audio"]) + } + output, ok := audio["output"].(map[string]any) + if !ok { + t.Fatalf("definition.audio.output = %#v, want object", audio["output"]) + } + + 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 service wire shape: %#v", output) + } +} + +func TestCreateVoiceAgentAPIRequest_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 := CreateVoiceAgentAPIRequest(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..e7435c054c3 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,98 @@ 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.ParallelToolCalls != nil { + errors = append(errors, + "template.parallel_tool_calls is not currently supported by the prompt voice runtime; remove it from azure.yaml") + } + + if agent.Audio == nil { + 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) == "" { + 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.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)...) + 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 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 { + 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/parse_voice_test.go b/cli/azd/extensions/azure.ai.agents/internal/pkg/agents/agent_yaml/parse_voice_test.go index 6aba8a368dd..ded2d4e520c 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,39 @@ model_type: unsupported t.Fatalf("expected invalid model_type error, got: %v", err) } } + +func TestValidateAgentDefinition_PromptVoice_RejectsParallelToolCalls(t *testing.T) { + yamlContent := []byte(` +kind: prompt-voice +name: voice-agent +model: + id: gpt-realtime +parallel_tool_calls: true +`) + err := ValidateAgentDefinition(yamlContent) + if err == nil || !strings.Contains(err.Error(), "parallel_tool_calls is not currently supported") { + t.Fatalf("expected parallel_tool_calls validation 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) + } +} 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/internal/project/service_target_agent.go b/cli/azd/extensions/azure.ai.agents/internal/project/service_target_agent.go index 3f4039392a2..40cea42a0a6 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 { @@ -538,15 +551,15 @@ 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, and unified deploys also record + // VERSION. 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. @@ -1376,13 +1389,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) } @@ -2144,19 +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" // 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 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, @@ -2187,25 +2196,37 @@ 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, deployOp, err := p.deployVoiceAgentRemote( + ctx, agentClient, request, azdEnv, progress, ) if err != nil { - return nil, exterrors.ServiceFromAzure(err, exterrors.OpCreateAgent) + return nil, exterrors.ServiceFromAzure(err, deployOp) + } + if err := validateVoiceAgentDeployResponse(agentObject); err != nil { + return nil, err } - 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 := buildVoiceWSProtocolURL(projectEndpoint, agentObject.Name) + versionKey := fmt.Sprintf("AGENT_%s_VERSION", serviceKey) + versionValue := agentObject.Versions.Latest.Version + endpointKey := fmt.Sprintf("AGENT_%s_ENDPOINT", serviceKey) + if _, setErr := p.azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{ + EnvName: p.env.Name, + Key: endpointKey, + Value: "", + }); setErr != nil { + return nil, fmt.Errorf("clearing voice agent environment variable %s: %w", endpointKey, setErr) + } for _, envVar := range []struct{ key, value string }{ {fmt.Sprintf("AGENT_%s_NAME", serviceKey), agentObject.Name}, - {fmt.Sprintf("AGENT_%s_ENDPOINT", serviceKey), baseEndpoint}, + {versionKey, versionValue}, + {fmt.Sprintf("AGENT_%s_PROJECT_ENDPOINT", serviceKey), strings.TrimRight(projectEndpoint, "/")}, + {endpointKey, baseEndpoint}, } { if _, setErr := p.azdClient.Environment().SetValue(ctx, &azdext.SetEnvRequest{ EnvName: p.env.Name, @@ -2230,6 +2251,60 @@ func (p *AgentServiceTargetProvider) deployVoiceAgent( return &azdext.ServiceDeployResult{Artifacts: artifacts}, nil } +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 strings.TrimSpace(agentObject.Versions.Latest.Version) == "" { + return fmt.Errorf("malformed voice agent service response: missing latest agent version") + } + return nil +} + +func (p *AgentServiceTargetProvider) deployVoiceAgentRemote( + ctx context.Context, + agentClient *agent_api.AgentClient, + request *agent_api.CreateAgentRequest, + azdEnv map[string]string, + progress azdext.ProgressReporter, +) (*agent_api.AgentObject, string, error) { + overriddenHost := azdEnv[voiceOverriddenHostEnvKey] + remoteAgent, getErr := agentClient.GetVoiceAgent( + ctx, request.Name, agent_api.AgentEndpointAPIVersion, overriddenHost, + ) + shouldUpdate, decisionErr := shouldUpdateVoiceAgent(remoteAgent, getErr) + if decisionErr != nil { + return nil, exterrors.OpGetAgent, decisionErr + } + if shouldUpdate { + progress("Updating voice agent using unified API") + updateRequest := &agent_api.UpdateAgentRequest{ + CreateAgentVersionRequest: request.CreateAgentVersionRequest, + } + agentObject, err := agentClient.UpdateVoiceAgent( + ctx, request.Name, updateRequest, agent_api.AgentEndpointAPIVersion, overriddenHost, + ) + return agentObject, exterrors.OpUpdateAgent, err + } + + progress("Creating voice agent using unified API") + agentObject, err := agentClient.CreateVoiceAgent(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 +} + // 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 228f5b24843..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 @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net" + "net/http" "os" "path/filepath" "strings" @@ -668,6 +669,63 @@ func TestAdoptServiceConfigIgnoresNilAndKeepsResolvedState(t *testing.T) { require.False(t, provider.serviceConfigResolved) } +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 TestValidateVoiceAgentDeployResponse(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) + require.NoError(t, err) + }) + + t.Run("missing name rejected", func(t *testing.T) { + err := validateVoiceAgentDeployResponse(&agent_api.AgentObject{}) + require.ErrorContains(t, err, "missing agent name") + }) + + 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") + }) +} + +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() @@ -2752,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() @@ -2772,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 @@ -2790,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") @@ -2809,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. 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": {