From b25e7120163afd7c59d10029936fcd9d2dc1de4a Mon Sep 17 00:00:00 2001 From: kaylieee Date: Thu, 3 Sep 2026 00:25:50 -0700 Subject: [PATCH 01/17] update samples to use agent endpoint --- sdk/ai/azure-ai-agents/README.md | 70 +++++--- .../CreateResponseWithConversation.java | 66 +++---- .../azure/ai/agents/MemorySearchAgent.java | 85 ++++----- .../ai/agents/MultipleAgentsConversation.java | 117 ++++++++----- .../com/azure/ai/agents/ReadmeSamples.java | 33 ++-- .../CodeInterpreterStreamingAsync.java | 116 +++++++------ .../CodeInterpreterStreamingSync.java | 85 ++++----- .../streaming/FunctionCallStreamingAsync.java | 128 ++++++++------ .../streaming/FunctionCallStreamingSync.java | 105 ++++++------ .../streaming/SimpleStreamingAsync.java | 103 ++++++----- .../agents/streaming/SimpleStreamingSync.java | 57 +++--- .../ai/agents/tools/AgentToAgentAsync.java | 61 ++++--- .../ai/agents/tools/AgentToAgentSync.java | 39 +++-- .../ai/agents/tools/AzureAISearchAsync.java | 64 ++++--- .../ai/agents/tools/AzureAISearchSync.java | 39 +++-- .../ai/agents/tools/AzureFunctionAsync.java | 61 +++---- .../ai/agents/tools/AzureFunctionSync.java | 40 +++-- .../agents/tools/BingCustomSearchAsync.java | 61 ++++--- .../ai/agents/tools/BingCustomSearchSync.java | 38 ++-- .../ai/agents/tools/BingGroundingAsync.java | 61 ++++--- .../ai/agents/tools/BingGroundingSync.java | 39 +++-- .../agents/tools/BrowserAutomationAsync.java | 61 ++++--- .../agents/tools/BrowserAutomationSync.java | 39 +++-- .../ai/agents/tools/CodeInterpreterAsync.java | 97 ++++++----- .../ai/agents/tools/CodeInterpreterSync.java | 58 ++++--- .../ai/agents/tools/ComputerUseAsync.java | 102 ++++++----- .../ai/agents/tools/ComputerUseSync.java | 84 +++++---- .../tools/CustomCodeInterpreterAsync.java | 61 ++++--- .../tools/CustomCodeInterpreterSync.java | 41 +++-- .../azure/ai/agents/tools/FabricAsync.java | 61 ++++--- .../azure/ai/agents/tools/FabricIQAsync.java | 60 ++++--- .../azure/ai/agents/tools/FabricIQSync.java | 35 ++-- .../com/azure/ai/agents/tools/FabricSync.java | 39 +++-- .../ai/agents/tools/FunctionCallAsync.java | 95 +++++----- .../ai/agents/tools/FunctionCallSync.java | 102 +++++------ .../ai/agents/tools/ImageGenerationAsync.java | 61 ++++--- .../ai/agents/tools/ImageGenerationSync.java | 39 +++-- .../com/azure/ai/agents/tools/McpAsync.java | 162 +++++++++--------- .../com/azure/ai/agents/tools/McpSync.java | 81 ++++----- .../agents/tools/McpWithConnectionAsync.java | 120 ++++++------- .../agents/tools/McpWithConnectionSync.java | 51 +++--- .../ai/agents/tools/MemorySearchAsync.java | 94 +++++----- .../ai/agents/tools/MemorySearchSync.java | 75 ++++---- .../azure/ai/agents/tools/OpenApiAsync.java | 61 ++++--- .../azure/ai/agents/tools/OpenApiSample.java | 66 +++---- .../azure/ai/agents/tools/OpenApiSync.java | 66 +++---- .../tools/OpenApiWithConnectionAsync.java | 61 ++++--- .../tools/OpenApiWithConnectionSync.java | 38 ++-- .../tools/SharePointGroundingAsync.java | 61 ++++--- .../agents/tools/SharePointGroundingSync.java | 39 +++-- .../azure/ai/agents/tools/WebSearchAsync.java | 77 ++++----- .../azure/ai/agents/tools/WebSearchSync.java | 58 ++++--- .../azure/ai/agents/tools/WorkIQAsync.java | 51 +++--- .../com/azure/ai/agents/tools/WorkIQSync.java | 35 ++-- 54 files changed, 1922 insertions(+), 1777 deletions(-) diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index aee2c3bc97e21..a405f4ea71ecd 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -268,17 +268,30 @@ conversationsClient.items().create( To scope conversation operations to a delegated end user, set `FOUNDRY_USER_IDENTITY` to an opaque application-generated value and apply it as the `x-ms-user-identity` header. The caller must have the `agents/endpoints/UserIdentityImpersonation/action` RBAC permission. See the sync [UserIdentityConversation.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/conversations/UserIdentityConversation.java) and async [UserIdentityConversationAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/conversations/UserIdentityConversationAsync.java) samples. +#### Configure the agent endpoint + +Before invoking the agent, point its endpoint at the version you just created and enable the OpenAI Responses protocol on it: + +```java com.azure.ai.agents.configure_agent_endpoint +AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + +agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); +``` + #### Text generation with Responses -And the final step that ties everything together, we pass the `AgentReference` and the `conversation.id()` as parameters for the `Response` creation: +With the agent endpoint configured, invoke the OpenAI Responses API through an agent-scoped OpenAI client: ```java com.azure.ai.agents.create_response -AgentReference agentReference = new AgentReference(agent.getName()).setVersion(agent.getVersion()); -Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder().conversation(conversation.id())); -// To extract Azure-specific response details: -AzureCreateResponseDetails azureResults = ResponsesClient.getAzureFields(response); +OpenAIClient agentScopedClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + +Response response = agentScopedClient.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); ``` ### Using Agent tools @@ -768,16 +781,16 @@ The synchronous streaming methods return `IterableStream`, ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); // Stream response - text is printed as it arrives -IterableStream events = - responsesClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), +try (StreamResponse events = openAIClient.responses().createStreaming( ResponseCreateParams.builder() - .input("Tell me a short story about a brave explorer.")); + .input("Tell me a short story about a brave explorer.") + .build())) { -for (ResponseStreamEvent event : events) { - responseAccumulator.accumulate(event); - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); + events.stream().forEach(event -> { + responseAccumulator.accumulate(event); + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + }); } System.out.println(); // newline after streamed text @@ -797,21 +810,34 @@ The asynchronous streaming methods return `Flux`, integrati ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); // Stream response asynchronously - text is printed as each chunk arrives -return responsesAsyncClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Tell me a short story about a brave explorer.")) - .doOnNext(event -> { +AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( + ResponseCreateParams.builder() + .input("Tell me a short story about a brave explorer.") + .build()); + +stream.subscribe(new AsyncStreamResponse.Handler() { + @Override + public void onNext(ResponseStreamEvent event) { responseAccumulator.accumulate(event); event.outputTextDelta() .ifPresent(textEvent -> System.out.print(textEvent.delta())); - }) - .then(Mono.fromCallable(() -> { + } + + @Override + public void onComplete(java.util.Optional error) { + // No-op: onCompleteFuture below signals completion. + } +}); + +return Mono.fromFuture(stream.onCompleteFuture()) + .doFinally(signal -> stream.close()) + .doOnSuccess(unused -> { System.out.println(); // newline after streamed text // Access the complete accumulated response Response response = responseAccumulator.response(); System.out.println("\nResponse ID: " + response.id()); + }); ``` See the full samples in [SimpleStreamingAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java), [FunctionCallStreamingAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java), and [CodeInterpreterStreamingAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java). diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java index 14ff30b420590..bcfd76133c5f4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java @@ -3,12 +3,17 @@ package com.azure.ai.agents; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; @@ -16,9 +21,11 @@ import com.openai.models.responses.ResponseOutputMessage; import com.openai.services.blocking.ConversationService; +import java.util.Collections; + /** - * This sample demonstrates how to use the createWithAgentConversation helper method - * to create a response with a conversation. + * This sample demonstrates how to invoke the OpenAI Responses API against a Prompt Agent, + * routing all traffic through the agent's endpoint URL. */ public class CreateResponseWithConversation { public static void main(String[] args) { @@ -32,21 +39,23 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - AgentVersionDetails agent = null; - String conversationId = null; + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant."); + String agentName = "my-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + System.out.printf("Agent created (id: %s, version: %s)%n", agent.getId(), agent.getVersion()); + String conversationId = null; try { - // Create a prompt agent - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant."); + // Point the agent endpoint at the newly created version and enable the OpenAI Responses protocol. + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - agent = agentsClient.createAgentVersion("my-agent", agentDefinition); - System.out.printf("Agent created (id: %s, version: %s)\n", agent.getId(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); // Create a conversation Conversation conversation = conversationService.create(); @@ -54,11 +63,10 @@ public static void main(String[] args) { System.out.println("Created conversation: " + conversationId); // Create a response using the conversation - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(conversationId) - .input("Hi, how can you help me?")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .conversation(conversationId) + .input("Hi, how can you help me?") + .build()); // Process and display the response System.out.println("\n=== Agent Response ==="); @@ -73,20 +81,16 @@ public static void main(String[] args) { } } System.out.println("Response ID: " + response.id()); - } catch (Exception e) { - System.err.println("Error: " + e.getMessage()); - e.printStackTrace(); } finally { - // Cleanup conversation if (conversationId != null) { - conversationService.delete(conversationId); - System.out.println("Conversation deleted."); - } - // Cleanup agent - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted."); + try { + conversationService.delete(conversationId); + System.out.println("Conversation deleted."); + } catch (Exception ignored) { + // best-effort cleanup + } } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java index 579f608fec56c..4a3e382a3268f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java @@ -3,17 +3,22 @@ package com.azure.ai.agents; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.MemorySearchPreviewTool; import com.azure.ai.agents.models.MemoryStoreDefaultDefinition; import com.azure.ai.agents.models.MemoryStoreDefaultOptions; import com.azure.ai.agents.models.MemoryStoreDetails; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; @@ -43,14 +48,12 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); BetaMemoryStoresClient memoryStoresClient = builder.beta().buildBetaMemoryStoresClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); - ResponsesClient responsesClient = builder.buildResponsesClient(); String memoryStoreName = "my_memory_store"; String agentName = "MyAgent"; String description = "Example memory store for conversations"; String scope = "user_123"; - AgentVersionDetails agent = null; String firstConversationId = null; String followUpConversationId = null; @@ -71,45 +74,47 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - agent = agentsClient.createAgentVersion(agentName, agentDefinition); - System.out.printf("Agent created (id: %s, version: %s)\n", agent.getId(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()).setVersion(agent.getVersion()); - - Conversation conversation = conversationService.create(); - firstConversationId = conversation.id(); - System.out.println("Created conversation (id: " + firstConversationId + ")"); - - - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(firstConversationId) - .input("I prefer dark roast coffee")); - System.out.println("Response output: " + getResponseText(response)); - - System.out.println("Waiting for memories to be stored..."); - sleepSeconds(MEMORY_WRITE_DELAY_SECONDS); - - Conversation newConversation = conversationService.create(); - followUpConversationId = newConversation.id(); - System.out.println("Created new conversation (id: " + followUpConversationId + ")"); - - Response followUpResponse = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(followUpConversationId) - .input("Please order my usual coffee")); - System.out.println("Response output: " + getResponseText(followUpResponse)); - - System.out.println("Sample completed successfully."); + // Create the agent version and point the agent endpoint at the new version. + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + try { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + + Conversation conversation = conversationService.create(); + firstConversationId = conversation.id(); + System.out.println("Created conversation (id: " + firstConversationId + ")"); + + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .conversation(firstConversationId) + .input("I prefer dark roast coffee") + .build()); + System.out.println("Response output: " + getResponseText(response)); + + System.out.println("Waiting for memories to be stored..."); + sleepSeconds(MEMORY_WRITE_DELAY_SECONDS); + + Conversation newConversation = conversationService.create(); + followUpConversationId = newConversation.id(); + System.out.println("Created new conversation (id: " + followUpConversationId + ")"); + + Response followUpResponse = openAIClient.responses().create(ResponseCreateParams.builder() + .conversation(followUpConversationId) + .input("Please order my usual coffee") + .build()); + System.out.println("Response output: " + getResponseText(followUpResponse)); + + System.out.println("Sample completed successfully."); + } finally { + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + } } finally { deleteConversation(conversationService, firstConversationId); deleteConversation(conversationService, followUpConversationId); - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } cleanupMemoryStore(memoryStoresClient, memoryStoreName); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java index 019292cbc34f0..fedadc52b539d 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java @@ -3,12 +3,17 @@ package com.azure.ai.agents; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.conversations.items.ItemCreateParams; import com.openai.models.conversations.items.ItemListPage; @@ -17,10 +22,14 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; +import java.util.Collections; + /** - * This sample how multiple agents can consume a centralized context source (conversation) and provide different responses - * based on it. + * This sample shows how multiple agents can consume a centralized context source (conversation) and provide different + * responses based on it. * + *

Each agent's identity is baked into its agent endpoint URL. To route requests to a specific agent, build an + * agent-scoped OpenAI client and call {@code responses().create(...)} through it.

*/ public class MultipleAgentsConversation { /** @@ -29,13 +38,12 @@ public class MultipleAgentsConversation { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); - // Code sample for creating an agent + AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .serviceVersion(AgentsServiceVersion.getLatest()) .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); ConversationService conversationsClient = builder.buildOpenAIClient().conversations(); // Setting up the conversation with initial messages @@ -46,47 +54,66 @@ public static void main(String[] args) { printConversationItems(conversationsClient, conversation.id(), 2); - // creating a new agent and their references for future responses - AgentVersionDetails agent1 = createPromptAgent(agentsClient, model, "weather-agent-1"); - AgentVersionDetails agent2 = createPromptAgent(agentsClient, model, "weather-agent-2"); - - AgentReference agent1Reference = new AgentReference(agent1.getName()).setVersion(agent1.getVersion()); - AgentReference agent2Reference = new AgentReference(agent2.getName()).setVersion(agent2.getVersion()); - - // Get response from agent1 - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agent1Reference), - ResponseCreateParams.builder().conversation(conversation.id())); - System.out.println("Agent response from: " + agent1.getName()); - System.out.println("\tResponse: " + response.output().get(0).asMessage().content().get(0).asOutputText().text()); - - // Add clarification to the conversation - addMessageToConversation(conversationsClient, conversation.id(), - "You can make assumptions based on historical data. Today is October 7th.", EasyInputMessage.Role.USER); - printConversationItems(conversationsClient, conversation.id(), 3); - - // Get follow-up response from agent1 - Response followUpResponse = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agent1Reference), - ResponseCreateParams.builder().conversation(conversation.id())); - System.out.println("Agent response from: " + agent1.getName()); - System.out.println("\tResponse: " + followUpResponse.output().get(0).asMessage().content().get(0).asOutputText().text()); - - // Provide all the past context and more to agent2 - addMessageToConversation(conversationsClient, conversation.id(), - "Provide suggestions opposite of what historical data indicates.", EasyInputMessage.Role.SYSTEM); - printConversationItems(conversationsClient, conversation.id(), 4); - - Response newMessageThread = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agent2Reference), - ResponseCreateParams.builder().conversation(conversation.id())); - System.out.println("Agent response from: " + agent2.getName()); - System.out.println("\tResponse: " + newMessageThread.output().get(0).asMessage().content().get(0).asOutputText().text()); + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model); + + // Create two agents and configure each agent's endpoint to route 100% of traffic to the newly created version. + String agent1Name = "weather-agent-1"; + String agent2Name = "weather-agent-2"; + AgentVersionDetails agent1 = agentsClient.createAgentVersion(agent1Name, agentDefinition); + try { + configureAgentEndpoint(agentsClient, agent1Name, agent1.getVersion()); + + AgentVersionDetails agent2 = agentsClient.createAgentVersion(agent2Name, agentDefinition); + try { + configureAgentEndpoint(agentsClient, agent2Name, agent2.getVersion()); + + OpenAIClient agent1Client = builder.buildAgentScopedOpenAIClient(agent1Name); + OpenAIClient agent2Client = builder.buildAgentScopedOpenAIClient(agent2Name); + + // Get response from agent1 + Response response = agent1Client.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); + System.out.println("Agent response from: " + agent1Name); + System.out.println("\tResponse: " + response.output().get(0).asMessage().content().get(0).asOutputText().text()); + + // Add clarification to the conversation + addMessageToConversation(conversationsClient, conversation.id(), + "You can make assumptions based on historical data. Today is October 7th.", EasyInputMessage.Role.USER); + printConversationItems(conversationsClient, conversation.id(), 3); + + // Get follow-up response from agent1 + Response followUpResponse = agent1Client.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); + System.out.println("Agent response from: " + agent1Name); + System.out.println("\tResponse: " + followUpResponse.output().get(0).asMessage().content().get(0).asOutputText().text()); + + // Provide all the past context and more to agent2 + addMessageToConversation(conversationsClient, conversation.id(), + "Provide suggestions opposite of what historical data indicates.", EasyInputMessage.Role.SYSTEM); + printConversationItems(conversationsClient, conversation.id(), 4); + + Response newMessageThread = agent2Client.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); + System.out.println("Agent response from: " + agent2Name); + System.out.println("\tResponse: " + newMessageThread.output().get(0).asMessage().content().get(0).asOutputText().text()); + } finally { + agentsClient.deleteAgentVersion(agent2Name, agent2.getVersion()); + } + } finally { + agentsClient.deleteAgentVersion(agent1Name, agent1.getVersion()); + } } - private static AgentVersionDetails createPromptAgent(AgentsClient agentsClient, String model, String name) { - PromptAgentDefinition request = new PromptAgentDefinition(model); - return agentsClient.createAgentVersion(name, request); + // Points the agent endpoint at the specified version and enables the OpenAI Responses protocol on it. + private static void configureAgentEndpoint(AgentsClient agentsClient, String agentName, String agentVersion) { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agentVersion)))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); } private static Conversation startConversation(ConversationService conversationsClient) { diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java index 14542ed8ad31f..1e88887489367 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java @@ -4,12 +4,15 @@ package com.azure.ai.agents; -import com.azure.ai.agents.models.AgentReference; +import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.AzureCreateResponseDetails; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; import com.azure.ai.agents.models.SessionLogEvent; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.IterableStream; import com.azure.identity.AuthenticationUtil; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -23,6 +26,8 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; +import java.util.Collections; + public final class ReadmeSamples { public void readmeSamples() { String endpoint = "my-resource-url"; @@ -31,7 +36,6 @@ public void readmeSamples() { AgentsClientBuilder builder = new AgentsClientBuilder(); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); ConversationService conversationsClient = builder.buildOpenAIClient().conversations(); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); @@ -45,6 +49,16 @@ public void readmeSamples() { AgentVersionDetails agent = agentsClient.createAgentVersion("my-agent", promptAgentDefinition); // END: com.azure.ai.agents.create_prompt_agent + // BEGIN: com.azure.ai.agents.configure_agent_endpoint + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + + agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + // END: com.azure.ai.agents.configure_agent_endpoint + // BEGIN: com.azure.ai.agents.create_conversation Conversation conversation = conversationsClient.create(); // END: com.azure.ai.agents.create_conversation @@ -66,12 +80,11 @@ public void readmeSamples() { // END: com.azure.ai.agents.add_message_to_conversation // BEGIN: com.azure.ai.agents.create_response - AgentReference agentReference = new AgentReference(agent.getName()).setVersion(agent.getVersion()); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder().conversation(conversation.id())); - // To extract Azure-specific response details: - AzureCreateResponseDetails azureResults = ResponsesClient.getAzureFields(response); + OpenAIClient agentScopedClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + + Response response = agentScopedClient.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); // END: com.azure.ai.agents.create_response // BEGIN: com.azure.ai.agents.openai_official_library diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java index b1c5145a1c313..12cad1775a19e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java @@ -5,21 +5,26 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; +import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to stream a response from an agent configured with the @@ -42,9 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create a CodeInterpreterTool - an Azure-specific tool for executing Python code CodeInterpreterTool tool = new CodeInterpreterTool(); @@ -55,53 +57,65 @@ public static void main(String[] args) { + "When asked to perform calculations, use the code interpreter to run Python code.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("code-interpreter-streaming-async-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, + // so responses.createStreaming(...) below does not need to send an agent_reference in its body. + String agentName = "code-interpreter-streaming-async-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); - // BEGIN: com.azure.ai.agents.streaming.code_interpreter_async - // Stream response asynchronously with Code Interpreter - ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + // BEGIN: com.azure.ai.agents.streaming.code_interpreter_async + // Stream response asynchronously with Code Interpreter + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - return responsesAsyncClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers using Python.")) - .doOnNext(event -> { - responseAccumulator.accumulate(event); - // Print text deltas as they arrive - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - // Observe code interpreter progress events - event.codeInterpreterCallInProgress() - .ifPresent(e -> System.out.println("\n[Code interpreter running...]")); - event.codeInterpreterCallCodeDelta() - .ifPresent(e -> System.out.print(e.delta())); - event.codeInterpreterCallCompleted() - .ifPresent(e -> System.out.println("\n[Code interpreter completed]")); - }) - .then(Mono.fromCallable(() -> { - System.out.println(); + .input("Calculate the first 10 prime numbers using Python.") + .build()); + + stream.subscribe(new AsyncStreamResponse.Handler() { + @Override + public void onNext(ResponseStreamEvent event) { + responseAccumulator.accumulate(event); + // Print text deltas as they arrive + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + // Observe code interpreter progress events + event.codeInterpreterCallInProgress() + .ifPresent(e -> System.out.println("\n[Code interpreter running...]")); + event.codeInterpreterCallCodeDelta() + .ifPresent(e -> System.out.print(e.delta())); + event.codeInterpreterCallCompleted() + .ifPresent(e -> System.out.println("\n[Code interpreter completed]")); + } + + @Override + public void onComplete(java.util.Optional error) { + // No-op: onCompleteFuture below signals completion. + } + }); + + return Mono.fromFuture(stream.onCompleteFuture()) + .doFinally(signal -> stream.close()) + .doOnSuccess(unused -> { + System.out.println(); - // Access the complete accumulated response - Response response = responseAccumulator.response(); - System.out.println("\nResponse ID: " + response.id()); - // END: com.azure.ai.agents.streaming.code_interpreter_async - return response; - })); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + // Access the complete accumulated response + Response response = responseAccumulator.response(); + System.out.println("\nResponse ID: " + response.id()); + }); + // END: com.azure.ai.agents.streaming.code_interpreter_async + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .block(); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java index b64d548bb3038..d595e7244bc9f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java @@ -5,19 +5,23 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; -import com.azure.core.util.IterableStream; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; +import com.openai.core.http.StreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseStreamEvent; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -42,49 +46,51 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - AgentVersionDetails agent = null; + // Create a CodeInterpreterTool - an Azure-specific tool for executing Python code + CodeInterpreterTool tool = new CodeInterpreterTool(); - try { - // Create a CodeInterpreterTool - an Azure-specific tool for executing Python code - CodeInterpreterTool tool = new CodeInterpreterTool(); + // Create agent with Code Interpreter tool + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " + + "When asked to perform calculations, use the code interpreter to run Python code.") + .setTools(Collections.singletonList(tool)); - // Create agent with Code Interpreter tool - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " - + "When asked to perform calculations, use the code interpreter to run Python code.") - .setTools(Collections.singletonList(tool)); + String agentName = "code-interpreter-streaming-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + try { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - agent = agentsClient.createAgentVersion("code-interpreter-streaming-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); // BEGIN: com.azure.ai.agents.streaming.code_interpreter_sync // Stream response with Code Interpreter - observe code execution events as they arrive ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - IterableStream events = - responsesClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + try (StreamResponse events = openAIClient.responses().createStreaming( ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers using Python.")); - - for (ResponseStreamEvent event : events) { - responseAccumulator.accumulate(event); - // Print text deltas as they stream in - event.outputTextDelta().ifPresent(textEvent -> - System.out.print(textEvent.delta())); - - // Observe code interpreter progress events - event.codeInterpreterCallInProgress().ifPresent(e -> - System.out.println("\n[Code interpreter running...]")); - event.codeInterpreterCallCodeDelta().ifPresent(e -> - System.out.print(e.delta())); - event.codeInterpreterCallCompleted().ifPresent(e -> - System.out.println("\n[Code interpreter completed]")); + .input("Calculate the first 10 prime numbers using Python.") + .build())) { + + events.stream().forEach(event -> { + responseAccumulator.accumulate(event); + // Print text deltas as they stream in + event.outputTextDelta().ifPresent(textEvent -> + System.out.print(textEvent.delta())); + + // Observe code interpreter progress events + event.codeInterpreterCallInProgress().ifPresent(e -> + System.out.println("\n[Code interpreter running...]")); + event.codeInterpreterCallCodeDelta().ifPresent(e -> + System.out.print(e.delta())); + event.codeInterpreterCallCompleted().ifPresent(e -> + System.out.println("\n[Code interpreter completed]")); + }); } System.out.println(); @@ -93,10 +99,7 @@ public static void main(String[] args) { System.out.println("\nResponse ID: " + response.id()); // END: com.azure.ai.agents.streaming.code_interpreter_sync } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java index c824adaca8e02..a4fa49d0b9cc9 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java @@ -5,27 +5,32 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; +import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; +import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to stream a response from an agent configured with a @@ -48,9 +53,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Define a function tool with parameter schema Map locationProp = new LinkedHashMap<>(); @@ -80,57 +82,69 @@ public static void main(String[] args) { + "When asked about the weather, use the get_weather function.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("function-streaming-async-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - // BEGIN: com.azure.ai.agents.streaming.function_call_async - // Stream response asynchronously with function tool - ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - - return responsesAsyncClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, + // so responses.createStreaming(...) below does not need to send an agent_reference in its body. + String agentName = "function-streaming-async-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + + // BEGIN: com.azure.ai.agents.streaming.function_call_async + // Stream response asynchronously with function tool + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + + AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( ResponseCreateParams.builder() - .input("What's the weather like in Seattle?")) - .doOnNext(event -> { - responseAccumulator.accumulate(event); - // Print text deltas as they arrive - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - // Print function call argument deltas as they arrive - event.functionCallArgumentsDelta() - .ifPresent(argEvent -> System.out.print(argEvent.delta())); - }) - .then(Mono.fromCallable(() -> { - System.out.println(); - - // Access the final response and inspect function calls - Response response = responseAccumulator.response(); - for (ResponseOutputItem outputItem : response.output()) { - outputItem.functionCall().ifPresent(functionCall -> { - System.out.println("\n--- Function Tool Call ---"); - System.out.println("Call ID: " + functionCall.callId()); - System.out.println("Function Name: " + functionCall.name()); - System.out.println("Arguments: " + functionCall.arguments()); - System.out.println("Status: " + functionCall.status()); - }); + .input("What's the weather like in Seattle?") + .build()); + + stream.subscribe(new AsyncStreamResponse.Handler() { + @Override + public void onNext(ResponseStreamEvent event) { + responseAccumulator.accumulate(event); + // Print text deltas as they arrive + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + // Print function call argument deltas as they arrive + event.functionCallArgumentsDelta() + .ifPresent(argEvent -> System.out.print(argEvent.delta())); + } + + @Override + public void onComplete(java.util.Optional error) { + // No-op: onCompleteFuture below signals completion. } - // END: com.azure.ai.agents.streaming.function_call_async - return response; - })); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + }); + + return Mono.fromFuture(stream.onCompleteFuture()) + .doFinally(signal -> stream.close()) + .doOnSuccess(unused -> { + System.out.println(); + + // Access the final response and inspect function calls + Response response = responseAccumulator.response(); + for (ResponseOutputItem outputItem : response.output()) { + outputItem.functionCall().ifPresent(functionCall -> { + System.out.println("\n--- Function Tool Call ---"); + System.out.println("Call ID: " + functionCall.callId()); + System.out.println("Function Name: " + functionCall.name()); + System.out.println("Arguments: " + functionCall.arguments()); + System.out.println("Status: " + functionCall.status()); + }); + } + }); + // END: com.azure.ai.agents.streaming.function_call_async + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .block(); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java index 9912a8aac1b6c..cc38eb94197fb 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java @@ -5,21 +5,25 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; -import com.azure.core.util.IterableStream; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; +import com.openai.core.http.StreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseStreamEvent; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -48,63 +52,65 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - AgentVersionDetails agent = null; + // Define a function tool with parameter schema + Map locationProp = new LinkedHashMap<>(); + locationProp.put("type", "string"); + locationProp.put("description", "The city and state, e.g. Seattle, WA"); - try { - // Define a function tool with parameter schema - Map locationProp = new LinkedHashMap<>(); - locationProp.put("type", "string"); - locationProp.put("description", "The city and state, e.g. Seattle, WA"); + Map unitProp = new LinkedHashMap<>(); + unitProp.put("type", "string"); + unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); - Map unitProp = new LinkedHashMap<>(); - unitProp.put("type", "string"); - unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); + Map properties = new LinkedHashMap<>(); + properties.put("location", locationProp); + properties.put("unit", unitProp); - Map properties = new LinkedHashMap<>(); - properties.put("location", locationProp); - properties.put("unit", unitProp); + Map parameters = new HashMap<>(); + parameters.put("type", BinaryData.fromObject("object")); + parameters.put("properties", BinaryData.fromObject(properties)); + parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); + parameters.put("additionalProperties", BinaryData.fromObject(false)); - Map parameters = new HashMap<>(); - parameters.put("type", BinaryData.fromObject("object")); - parameters.put("properties", BinaryData.fromObject(properties)); - parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); - parameters.put("additionalProperties", BinaryData.fromObject(false)); + FunctionTool tool = new FunctionTool("get_weather", parameters, true) + .setDescription("Get the current weather in a given location"); - FunctionTool tool = new FunctionTool("get_weather", parameters, true) - .setDescription("Get the current weather in a given location"); + // Create agent with function tool + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can get weather information. " + + "When asked about the weather, use the get_weather function.") + .setTools(Collections.singletonList(tool)); - // Create agent with function tool - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can get weather information. " - + "When asked about the weather, use the get_weather function.") - .setTools(Collections.singletonList(tool)); + String agentName = "function-streaming-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + try { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - agent = agentsClient.createAgentVersion("function-streaming-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); // BEGIN: com.azure.ai.agents.streaming.function_call_sync // Stream response with function tool - observe function call arguments and text as they arrive ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - IterableStream events = - responsesClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + try (StreamResponse events = openAIClient.responses().createStreaming( ResponseCreateParams.builder() - .input("What's the weather like in Seattle?")); - - for (ResponseStreamEvent event : events) { - responseAccumulator.accumulate(event); - // Print text deltas as they stream in - event.outputTextDelta().ifPresent(textEvent -> - System.out.print(textEvent.delta())); - // Print function call argument deltas as they stream in - event.functionCallArgumentsDelta().ifPresent(argEvent -> - System.out.print(argEvent.delta())); + .input("What's the weather like in Seattle?") + .build())) { + + events.stream().forEach(event -> { + responseAccumulator.accumulate(event); + // Print text deltas as they stream in + event.outputTextDelta().ifPresent(textEvent -> + System.out.print(textEvent.delta())); + // Print function call argument deltas as they stream in + event.functionCallArgumentsDelta().ifPresent(argEvent -> + System.out.print(argEvent.delta())); + }); } System.out.println(); @@ -121,10 +127,7 @@ public static void main(String[] args) { } // END: com.azure.ai.agents.streaming.function_call_sync } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java index 6748c0d1a5396..a4dab798949f1 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java @@ -5,19 +5,25 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; +import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; -import java.util.concurrent.atomic.AtomicReference; +import java.util.Collections; /** * This sample demonstrates how to create a streaming response using the asynchronous client. @@ -39,54 +45,63 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create an agent PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) .setInstructions("You are a helpful assistant that tells short, engaging stories."); - agentsAsyncClient.createAgentVersion("streaming-async-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, + // so responses.createStreaming(...) below does not need to send an agent_reference in its body. + String agentName = "streaming-async-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); - // BEGIN: com.azure.ai.agents.streaming.simple_async - // Use ResponseAccumulator to collect streamed events into a final Response - ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + // BEGIN: com.azure.ai.agents.streaming.simple_async + // Use ResponseAccumulator to collect streamed events into a final Response + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - // Stream response asynchronously - text is printed as each chunk arrives - return responsesAsyncClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + // Stream response asynchronously - text is printed as each chunk arrives + AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( ResponseCreateParams.builder() - .input("Tell me a short story about a brave explorer.")) - .doOnNext(event -> { - responseAccumulator.accumulate(event); - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - }) - .then(Mono.fromCallable(() -> { - System.out.println(); // newline after streamed text + .input("Tell me a short story about a brave explorer.") + .build()); + + stream.subscribe(new AsyncStreamResponse.Handler() { + @Override + public void onNext(ResponseStreamEvent event) { + responseAccumulator.accumulate(event); + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + } + + @Override + public void onComplete(java.util.Optional error) { + // No-op: onCompleteFuture below signals completion. + } + }); + + return Mono.fromFuture(stream.onCompleteFuture()) + .doFinally(signal -> stream.close()) + .doOnSuccess(unused -> { + System.out.println(); // newline after streamed text - // Access the complete accumulated response - Response response = responseAccumulator.response(); - System.out.println("\nResponse ID: " + response.id()); - // END: com.azure.ai.agents.streaming.simple_async - return response; - })); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + // Access the complete accumulated response + Response response = responseAccumulator.response(); + System.out.println("\nResponse ID: " + response.id()); + }); + // END: com.azure.ai.agents.streaming.simple_async + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .block(); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java index 053df3c69070f..11596336ef8b0 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java @@ -5,19 +5,25 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; -import com.azure.core.util.IterableStream; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; +import com.openai.core.http.StreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseStreamEvent; +import java.util.Collections; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; + /** * This sample demonstrates how to create a streaming response using the synchronous client. * Text is printed as it arrives rather than waiting for the full response. @@ -38,36 +44,38 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - AgentVersionDetails agent = null; + // Create an agent + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that tells short, engaging stories."); + String agentName = "streaming-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create an agent - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that tells short, engaging stories."); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - agent = agentsClient.createAgentVersion("streaming-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); // BEGIN: com.azure.ai.agents.streaming.simple_sync // Use ResponseAccumulator to collect streamed events into a final Response ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); // Stream response - text is printed as it arrives - IterableStream events = - responsesClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + try (StreamResponse events = openAIClient.responses().createStreaming( ResponseCreateParams.builder() - .input("Tell me a short story about a brave explorer.")); + .input("Tell me a short story about a brave explorer.") + .build())) { - for (ResponseStreamEvent event : events) { - responseAccumulator.accumulate(event); - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); + events.stream().forEach(event -> { + responseAccumulator.accumulate(event); + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + }); } System.out.println(); // newline after streamed text @@ -76,10 +84,7 @@ public static void main(String[] args) { System.out.println("\nResponse ID: " + response.id()); // END: com.azure.ai.agents.streaming.simple_sync } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java index 3bc983de53fd0..65774d70739f7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java @@ -5,20 +5,23 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; import com.azure.ai.agents.models.A2AProtocolVersion; import com.azure.ai.agents.models.A2ATool; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with an Agent-to-Agent (A2A) tool @@ -42,9 +45,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create agent-to-agent tool with A2A protocol version and connection ID A2ATool a2aTool = new A2ATool(A2AProtocolVersion.V1_0) @@ -54,30 +54,27 @@ public static void main(String[] args) { .setInstructions("You are a coordinator agent that can communicate with other agents.") .setTools(Collections.singletonList(a2aTool)); - agentsAsyncClient.createAgentVersion("a2a-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What can the secondary agent do?")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "a2a-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("What can the secondary agent do?") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java index 35a1e34f7be9d..f8888ed22c210 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java @@ -5,17 +5,21 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; import com.azure.ai.agents.models.A2AProtocolVersion; import com.azure.ai.agents.models.A2ATool; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -41,7 +45,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_agent_to_agent // Create agent-to-agent tool with A2A protocol version and connection ID @@ -54,23 +57,25 @@ public static void main(String[] args) { .setInstructions("You are a coordinator agent that can communicate with other agents.") .setTools(Collections.singletonList(a2aTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("a2a-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "a2a-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What can the secondary agent do?")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("What can the secondary agent do?") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java index d96b5a34e1922..6d91192625e6c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java @@ -5,23 +5,27 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; import com.azure.ai.agents.models.AISearchIndexResource; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AzureAISearchQueryType; import com.azure.ai.agents.models.AzureAISearchTool; import com.azure.ai.agents.models.AzureAISearchToolResource; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; +import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; + import java.time.Duration; import java.util.Arrays; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; -import reactor.core.publisher.Mono; /** * This sample demonstrates (using the async client) how to create an agent with the Azure AI Search tool @@ -47,9 +51,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create Azure AI Search tool with index configuration AzureAISearchTool aiSearchTool = new AzureAISearchTool( @@ -66,30 +67,27 @@ public static void main(String[] args) { + "Always provide citations for answers using the tool.") .setTools(Collections.singletonList(aiSearchTool)); - agentsAsyncClient.createAgentVersion("ai-search-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Search for information about Azure AI services")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, + // so responses.create(...) below does not need to send an agent_reference in its body. + String agentName = "ai-search-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Search for information about Azure AI services") + .build())) + .doOnNext(response -> System.out.println("Response: " + response.output())); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java index 6e0190bb9527e..7688aef2d2c42 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AISearchIndexResource; import com.azure.ai.agents.models.AzureAISearchQueryType; import com.azure.ai.agents.models.AzureAISearchTool; @@ -16,8 +12,16 @@ import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -46,7 +50,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_azure_ai_search // Create Azure AI Search tool with index configuration @@ -66,23 +69,25 @@ public static void main(String[] args) { + "Always provide citations for answers using the tool.") .setTools(Collections.singletonList(aiSearchTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("ai-search-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "ai-search-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Search for information about Azure AI services")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Search for information about Azure AI services") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java index d70d71ccaff81..eb5072e0ed550 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AzureFunctionBinding; import com.azure.ai.agents.models.AzureFunctionDefinition; import com.azure.ai.agents.models.AzureFunctionDefinitionDetails; @@ -18,16 +14,23 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ToolChoiceOptions; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an Azure Function tool @@ -55,9 +58,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); Map locationProp = new LinkedHashMap(); locationProp.put("type", "string"); @@ -85,31 +85,26 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(azureFunctionTool)); - agentsAsyncClient.createAgentVersion("azure-function-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .toolChoice(ToolChoiceOptions.REQUIRED) - .input("What is the weather in Seattle?")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "azure-function-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .toolChoice(ToolChoiceOptions.REQUIRED) + .input("What is the weather in Seattle?") + .build())) + .doOnNext(response -> System.out.println("Response: " + response.output())); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java index 9fb27334bf6e9..441187c78fc67 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AzureFunctionBinding; import com.azure.ai.agents.models.AzureFunctionDefinition; import com.azure.ai.agents.models.AzureFunctionDefinitionDetails; @@ -18,9 +14,17 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ToolChoiceOptions; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.HashMap; @@ -53,7 +57,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // Define function parameters // Use BinaryData.fromObject() to produce correct JSON types @@ -87,23 +90,26 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(azureFunctionTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("azure-function-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "azure-function-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .toolChoice(ToolChoiceOptions.REQUIRED) - .input("What is the weather in Seattle?")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .toolChoice(ToolChoiceOptions.REQUIRED) + .input("What is the weather in Seattle?") + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java index 6169c2f7027c6..70f24d650c5a1 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingCustomSearchConfiguration; import com.azure.ai.agents.models.BingCustomSearchPreviewTool; import com.azure.ai.agents.models.BingCustomSearchToolParameters; @@ -17,11 +13,18 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Arrays; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with the Bing Custom Search tool @@ -47,9 +50,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); BingCustomSearchPreviewTool bingCustomSearchTool = new BingCustomSearchPreviewTool( new BingCustomSearchToolParameters(Arrays.asList( @@ -62,30 +62,27 @@ public static void main(String[] args) { + "Use the available Bing Custom Search tools to answer questions and perform tasks.") .setTools(Collections.singletonList(bingCustomSearchTool)); - agentsAsyncClient.createAgentVersion("bing-custom-search-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Search for the latest Azure AI documentation")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "bing-custom-search-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Search for the latest Azure AI documentation") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java index 0851bae06249b..3012a7c5b5ade 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingCustomSearchConfiguration; import com.azure.ai.agents.models.BingCustomSearchPreviewTool; import com.azure.ai.agents.models.BingCustomSearchToolParameters; @@ -17,6 +13,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -50,7 +54,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_bing_custom_search // Create Bing Custom Search tool with connection and instance configuration @@ -67,22 +70,25 @@ public static void main(String[] args) { + "Use the available Bing Custom Search tools to answer questions and perform tasks.") .setTools(Collections.singletonList(bingCustomSearchTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("bing-custom-search-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "bing-custom-search-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Search for the latest Azure AI documentation")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Search for the latest Azure AI documentation") + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java index 2cbfbed36da81..5a3aadfe86a1f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingGroundingSearchConfiguration; import com.azure.ai.agents.models.BingGroundingSearchToolParameters; import com.azure.ai.agents.models.BingGroundingTool; @@ -19,8 +15,15 @@ import java.time.Duration; import java.util.Arrays; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Bing Grounding tool @@ -44,9 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create Bing grounding tool with connection configuration BingGroundingTool bingTool = new BingGroundingTool( @@ -59,30 +59,27 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant. Use Bing to find up-to-date information.") .setTools(Collections.singletonList(bingTool)); - agentsAsyncClient.createAgentVersion("bing-grounding-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What are the latest developments in AI?")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "bing-grounding-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("What are the latest developments in AI?") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java index a5f1dc4bc8dfe..86b09062a7d31 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingGroundingSearchConfiguration; import com.azure.ai.agents.models.BingGroundingSearchToolParameters; import com.azure.ai.agents.models.BingGroundingTool; @@ -17,6 +13,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Arrays; @@ -43,7 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_bing_grounding // Create Bing grounding tool with connection configuration @@ -59,23 +62,25 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant. Use Bing to find up-to-date information.") .setTools(Collections.singletonList(bingTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("bing-grounding-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "bing-grounding-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What are the latest developments in AI?")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("What are the latest developments in AI?") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java index b4ff5cf914bee..129f9026c4abd 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BrowserAutomationPreviewTool; import com.azure.ai.agents.models.BrowserAutomationToolConnectionParameters; import com.azure.ai.agents.models.BrowserAutomationToolParameters; @@ -18,8 +14,15 @@ import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Browser Automation tool @@ -43,9 +46,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create browser automation tool with connection configuration BrowserAutomationPreviewTool browserTool = new BrowserAutomationPreviewTool( @@ -58,30 +58,27 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can interact with web pages.") .setTools(Collections.singletonList(browserTool)); - agentsAsyncClient.createAgentVersion("browser-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Navigate to microsoft.com and summarize the main content")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "browser-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Navigate to microsoft.com and summarize the main content") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java index 81f42044575ad..2e4da2377f9fd 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BrowserAutomationPreviewTool; import com.azure.ai.agents.models.BrowserAutomationToolConnectionParameters; import com.azure.ai.agents.models.BrowserAutomationToolParameters; @@ -17,6 +13,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -42,7 +46,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_browser_automation // Create browser automation tool with connection configuration @@ -58,23 +61,25 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can interact with web pages.") .setTools(Collections.singletonList(browserTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("browser-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "browser-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Navigate to microsoft.com and summarize the main content")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Navigate to microsoft.com and summarize the main content") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java index e456e472fd210..3f0276f8a805d 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java @@ -5,23 +5,26 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCodeInterpreterToolCall; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create an agent with the Code Interpreter tool @@ -43,9 +46,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create a CodeInterpreterTool with default auto container configuration CodeInterpreterTool tool = new CodeInterpreterTool(); @@ -55,49 +55,48 @@ public static void main(String[] args) { + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("code-interpreter-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers and show me the Python code you used.")); - }) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); - }); - } + // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, + // so responses.create(...) below does not need to send an agent_reference in its body. + String agentName = "code-interpreter-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Calculate the first 10 prime numbers and show me the Python code you used.") + .build())) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); + }); + } - if (outputItem.codeInterpreterCall().isPresent()) { - ResponseCodeInterpreterToolCall codeCall = outputItem.codeInterpreterCall().get(); - System.out.println("\n--- Code Interpreter Execution ---"); - System.out.println("Call ID: " + codeCall.id()); - codeCall.code().ifPresent(code -> { - System.out.println("Python Code Executed:\n" + code); + if (outputItem.codeInterpreterCall().isPresent()) { + ResponseCodeInterpreterToolCall codeCall = outputItem.codeInterpreterCall().get(); + System.out.println("\n--- Code Interpreter Execution ---"); + System.out.println("Call ID: " + codeCall.id()); + codeCall.code().ifPresent(code -> { + System.out.println("Python Code Executed:\n" + code); + }); + System.out.println("Status: " + codeCall.status()); + } + } }); - System.out.println("Status: " + codeCall.status()); - } - } - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java index 2d1881b34f13c..0d2d2a5254836 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java @@ -5,19 +5,23 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCodeInterpreterToolCall; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -41,32 +45,33 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - AgentVersionDetails agent = null; + // BEGIN: com.azure.ai.agents.define_code_interpreter + // Create a CodeInterpreterTool with default auto container configuration + CodeInterpreterTool tool = new CodeInterpreterTool(); + // END: com.azure.ai.agents.define_code_interpreter - try { - // BEGIN: com.azure.ai.agents.define_code_interpreter - // Create a CodeInterpreterTool with default auto container configuration - CodeInterpreterTool tool = new CodeInterpreterTool(); - // END: com.azure.ai.agents.define_code_interpreter + // Create the agent definition with Code Interpreter tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " + + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") + .setTools(Collections.singletonList(tool)); - // Create the agent definition with Code Interpreter tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " - + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") - .setTools(Collections.singletonList(tool)); + String agentName = "code-interpreter-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + try { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - agent = agentsClient.createAgentVersion("code-interpreter-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers and show me the Python code you used.")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Calculate the first 10 prime numbers and show me the Python code you used.") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -90,10 +95,7 @@ public static void main(String[] args) { } } } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java index e446e08f50c09..b15401db0e424 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java @@ -6,10 +6,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.AgentsServiceVersion; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ComputerEnvironment; import com.azure.ai.agents.models.ComputerUsePreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -18,6 +14,7 @@ import com.azure.ai.agents.tools.ComputerUseUtil.SearchState; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.EasyInputMessage; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseComputerToolCall; @@ -29,13 +26,19 @@ import com.openai.models.responses.ResponseInputText; import com.openai.models.responses.ResponseOutputItem; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** @@ -72,7 +75,6 @@ public static void main(String[] args) { .serviceVersion(AgentsServiceVersion.getLatest()); AgentsAsyncClient agentsClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesClient = builder.buildResponsesAsyncClient(); // Load screenshot assets Map screenshots; @@ -96,9 +98,6 @@ public static void main(String[] args) { + "Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.") .setTools(Collections.singletonList(tool)); - // Use AtomicReference to track the agent for cleanup - AtomicReference agentRef = new AtomicReference<>(); - // Build the initial input using proper OpenAI SDK types List contentParts = Arrays.asList( // Text part @@ -123,48 +122,45 @@ public static void main(String[] args) { .build()) ); - // Create agent and run the interaction loop - agentsClient.createAgentVersion("ComputerUseAgent", agentDefinition) - .doOnNext(agent -> { - agentRef.set(agent); - System.out.printf("Agent created (id: %s, name: %s, version: %s)%n", - agent.getId(), agent.getName(), agent.getVersion()); - }) - .flatMap(agent -> { - // Create the AgentReference for the response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); - - // Send initial request - return responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() + final Map screenshotsForLoop = screenshots; + + // Create the agent version, pin the agent endpoint to it, then run the interaction loop + // through an agent-scoped OpenAI client. The endpoint URL identifies the agent, so + // responses.create(...) below does not need to send an agent_reference in its body. + String agentName = "ComputerUseAgent"; + Mono.usingWhen( + agentsClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + + System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); + + // Send initial request + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() .inputOfResponse(initialInput) - .truncation(ResponseCreateParams.Truncation.AUTO)) - .doOnNext(response -> System.out.printf("Initial response received (ID: %s)%n", response.id())) - .flatMap(response -> runInteractionLoop( - responsesClient, agentReference, response, screenshots, SearchState.INITIAL, 0)); - }) - .doFinally(signalType -> { - System.out.println("\nCleaning up..."); - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")) - .doOnError(e -> System.out.println("Failed to delete agent: " + e.getMessage())) - .subscribe(); - } - }) - .block(); // Block to wait for completion in main method + .truncation(ResponseCreateParams.Truncation.AUTO) + .build())) + .doOnNext(response -> System.out.printf("Initial response received (ID: %s)%n", response.id())) + .flatMap(response -> runInteractionLoop( + openAIAsyncClient, response, screenshotsForLoop, SearchState.INITIAL, 0)); + }, + agent -> agentsClient.deleteAgentVersion(agentName, agent.getVersion())) + .doOnError(e -> System.err.println("Error: " + e.getMessage())) + .block(); } /** * Recursively processes the interaction loop with the Computer Use Agent. * - * @param responsesClient The responses async client. - * @param agentReference The agent reference. + * @param openAIAsyncClient The agent-scoped OpenAI async client. * @param response The current response from the agent. * @param screenshots The map of screenshot assets. * @param currentState The current search state. @@ -172,8 +168,7 @@ public static void main(String[] args) { * @return A Mono that completes when the loop finishes. */ private static Mono runInteractionLoop( - ResponsesAsyncClient responsesClient, - AgentReference agentReference, + OpenAIClientAsync openAIAsyncClient, Response response, Map screenshots, SearchState currentState, @@ -222,14 +217,13 @@ private static Mono runInteractionLoop( .build()) ); - return responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .previousResponseId(response.id()) - .inputOfResponse(followUpInput) - .truncation(ResponseCreateParams.Truncation.AUTO)) + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .previousResponseId(response.id()) + .inputOfResponse(followUpInput) + .truncation(ResponseCreateParams.Truncation.AUTO) + .build())) .doOnNext(newResponse -> System.out.printf("Follow-up response received (ID: %s)%n", newResponse.id())) .flatMap(newResponse -> runInteractionLoop( - responsesClient, agentReference, newResponse, screenshots, newState, iteration + 1)); + openAIAsyncClient, newResponse, screenshots, newState, iteration + 1)); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java index cf1cc52d20453..b8b472bfb672f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java @@ -6,10 +6,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.AgentsServiceVersion; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ComputerEnvironment; import com.azure.ai.agents.models.ComputerUsePreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -18,6 +14,7 @@ import com.azure.ai.agents.tools.ComputerUseUtil.SearchState; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.EasyInputMessage; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseComputerToolCall; @@ -28,6 +25,13 @@ import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseInputText; import com.openai.models.responses.ResponseOutputItem; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.io.IOException; import java.util.Arrays; @@ -68,7 +72,6 @@ public static void main(String[] args) { .serviceVersion(AgentsServiceVersion.getLatest()); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // Initialize state machine SearchState currentState = SearchState.INITIAL; @@ -84,29 +87,30 @@ public static void main(String[] args) { return; } - AgentVersionDetails agent = null; - + // BEGIN: com.azure.ai.agents.define_computer_use + ComputerUsePreviewTool tool = new ComputerUsePreviewTool( + ComputerEnvironment.WINDOWS, + 1026, + 769 + ); + // END: com.azure.ai.agents.define_computer_use + + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a computer automation assistant." + + "Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.") + .setTools(Collections.singletonList(tool)); + + String agentName = "ComputerUseAgent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // BEGIN: com.azure.ai.agents.define_computer_use - ComputerUsePreviewTool tool = new ComputerUsePreviewTool( - ComputerEnvironment.WINDOWS, - 1026, - 769 - ); - // END: com.azure.ai.agents.define_computer_use + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a computer automation assistant." - + "Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.") - .setTools(Collections.singletonList(tool)); - agent = agentsClient.createAgentVersion("ComputerUseAgent", agentDefinition); - System.out.printf("Agent created (id: %s, name: %s, version: %s)%n", - agent.getId(), agent.getName(), agent.getVersion()); - - // Create the AgentReference for the response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); // Initial request with screenshot - start with Bing search page System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); @@ -136,11 +140,10 @@ public static void main(String[] args) { .build()) ); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .inputOfResponse(initialInput) - .truncation(ResponseCreateParams.Truncation.AUTO)); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .inputOfResponse(initialInput) + .truncation(ResponseCreateParams.Truncation.AUTO) + .build()); System.out.printf("Initial response received (ID: %s)%n", response.id()); @@ -193,25 +196,16 @@ public static void main(String[] args) { .build()) ); - response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .previousResponseId(response.id()) - .inputOfResponse(followUpInput) - .truncation(ResponseCreateParams.Truncation.AUTO)); + response = openAIClient.responses().create(ResponseCreateParams.builder() + .previousResponseId(response.id()) + .inputOfResponse(followUpInput) + .truncation(ResponseCreateParams.Truncation.AUTO) + .build()); System.out.printf("Follow-up response received (ID: %s)%n", response.id()); } } finally { - System.out.println("\nCleaning up..."); - if (agent != null) { - try { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } catch (Exception e) { - System.out.println("Failed to delete agent: " + e.getMessage()); - } - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java index 32cd8ec4d61c6..f72a04ffc8570 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java @@ -5,20 +5,23 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with a Custom Code Interpreter @@ -44,9 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); McpTool customCodeInterpreter = new McpTool("custom-code-interpreter") .setServerUrl(mcpServerUrl) @@ -57,30 +57,27 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.") .setTools(Collections.singletonList(customCodeInterpreter)); - agentsAsyncClient.createAgentVersion("CustomCodeInterpreterAgent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Calculate the factorial of 10 using Python.")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "CustomCodeInterpreterAgent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Calculate the factorial of 10 using Python.") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java index 123d1df73c2c5..87eb03080598d 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java @@ -5,16 +5,20 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -42,7 +46,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // Create custom code interpreter MCP tool // Uses require_approval: "never" because code runs in a sandboxed Container Apps session @@ -55,25 +58,25 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.") .setTools(Collections.singletonList(customCodeInterpreter)); - AgentVersionDetails agent = agentsClient.createAgentVersion( - "CustomCodeInterpreterAgent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "CustomCodeInterpreterAgent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Calculate the factorial of 10 using Python.")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Calculate the factorial of 10 using Python.") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java index 5ea819e4b43fa..7d3122e5f70a4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricDataAgentToolParameters; import com.azure.ai.agents.models.MicrosoftFabricPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -19,8 +15,15 @@ import java.time.Duration; import java.util.Arrays; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Microsoft Fabric tool @@ -44,9 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create Microsoft Fabric tool with connection configuration MicrosoftFabricPreviewTool fabricTool = new MicrosoftFabricPreviewTool( @@ -60,30 +60,27 @@ public static void main(String[] args) { .setInstructions("You are a data assistant that can query Microsoft Fabric data.") .setTools(Collections.singletonList(fabricTool)); - agentsAsyncClient.createAgentVersion("fabric-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Query the latest sales data from Microsoft Fabric")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "fabric-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Query the latest sales data from Microsoft Fabric") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java index 0bcb498f6600c..ddf3b565389b4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java @@ -5,19 +5,23 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricIqPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; @@ -48,7 +52,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); FabricIqPreviewTool fabricIqTool = new FabricIqPreviewTool(fabricIqConnectionId) .setServerLabel("fabric-iq-tool") @@ -58,32 +61,27 @@ public static void main(String[] args) { .setInstructions("Use the available Fabric IQ tools to answer questions and perform tasks.") .setTools(Collections.singletonList(fabricIqTool)); - Mono workflow = Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition), - agent -> { - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input(userInput)) - .doOnNext(FabricIQAsync::printResponse) - .then(); - }, - agent -> cleanup(agentsAsyncClient, agent), - (agent, error) -> cleanup(agentsAsyncClient, agent), - agent -> cleanup(agentsAsyncClient, agent)) - .timeout(Duration.ofSeconds(300)); - - workflow.block(); - } - - private static Mono cleanup(AgentsAsyncClient agentsAsyncClient, AgentVersionDetails agent) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input(userInput) + .build())) + .doOnNext(FabricIQAsync::printResponse); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .doOnError(error -> System.err.println("Error: " + error.getMessage())) + .timeout(Duration.ofSeconds(300)) + .block(); } private static void printResponse(Response response) { diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java index 8e107e6935dbf..6cda112edd784 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricIqPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -17,6 +13,14 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -46,7 +50,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_fabric_iq @@ -61,21 +64,23 @@ public static void main(String[] args) { .setTools(Collections.singletonList(fabricIqTool)); AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - try { - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input(userInput)); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input(userInput) + .build()); printResponse(response); } finally { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java index 79fa6a4d20726..47e353e62e500 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricDataAgentToolParameters; import com.azure.ai.agents.models.MicrosoftFabricPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -17,6 +13,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Arrays; @@ -43,7 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_fabric // Create Microsoft Fabric tool with connection configuration @@ -60,23 +63,25 @@ public static void main(String[] args) { .setInstructions("You are a data assistant that can query Microsoft Fabric data.") .setTools(Collections.singletonList(fabricTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("fabric-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "fabric-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Query the latest sales data from Microsoft Fabric")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Query the latest sales data from Microsoft Fabric") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java index 48b253e2823da..5f0610eb1e8ee 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; @@ -19,6 +15,14 @@ import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Arrays; @@ -26,7 +30,6 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create an agent with a Function Calling tool @@ -48,9 +51,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create a FunctionTool with parameters schema // Use BinaryData.fromObject() to produce correct JSON types (not double-encoded strings) @@ -81,48 +81,45 @@ public static void main(String[] args) { + "When asked about the weather, use the get_weather function to retrieve weather data.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("function-call-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What's the weather like in Seattle?")); - }) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); + String agentName = "function-call-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("What's the weather like in Seattle?") + .build())) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); + }); + } + + if (outputItem.functionCall().isPresent()) { + ResponseFunctionToolCall functionCall = outputItem.functionCall().get(); + System.out.println("\n--- Function Tool Call ---"); + System.out.println("Call ID: " + functionCall.callId()); + System.out.println("Function Name: " + functionCall.name()); + System.out.println("Arguments: " + functionCall.arguments()); + System.out.println("Status: " + functionCall.status()); + } + } }); - } - - if (outputItem.functionCall().isPresent()) { - ResponseFunctionToolCall functionCall = outputItem.functionCall().get(); - System.out.println("\n--- Function Tool Call ---"); - System.out.println("Call ID: " + functionCall.callId()); - System.out.println("Function Name: " + functionCall.name()); - System.out.println("Arguments: " + functionCall.arguments()); - System.out.println("Status: " + functionCall.status()); - } - } - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(30)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java index f1bce62bfeecb..bf14007c48ca7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java @@ -5,20 +5,24 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseFunctionToolCall; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -46,50 +50,51 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - - AgentVersionDetails agent = null; + // Create a FunctionTool with parameters schema + // Use BinaryData.fromObject() to produce correct JSON types (not double-encoded strings) + Map locationProp = new LinkedHashMap(); + locationProp.put("type", "string"); + locationProp.put("description", "The city and state, e.g. Seattle, WA"); + + Map unitProp = new LinkedHashMap(); + unitProp.put("type", "string"); + unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); + + Map properties = new LinkedHashMap(); + properties.put("location", locationProp); + properties.put("unit", unitProp); + + Map parameters = new HashMap(); + parameters.put("type", BinaryData.fromObject("object")); + parameters.put("properties", BinaryData.fromObject(properties)); + parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); + parameters.put("additionalProperties", BinaryData.fromObject(false)); + + FunctionTool tool = new FunctionTool("get_weather", parameters, true) + .setDescription("Get the current weather in a given location"); + + // Create the agent definition with Function tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can get weather information. " + + "When asked about the weather, use the get_weather function to retrieve weather data.") + .setTools(Collections.singletonList(tool)); + + String agentName = "function-call-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a FunctionTool with parameters schema - // Use BinaryData.fromObject() to produce correct JSON types (not double-encoded strings) - Map locationProp = new LinkedHashMap(); - locationProp.put("type", "string"); - locationProp.put("description", "The city and state, e.g. Seattle, WA"); - - Map unitProp = new LinkedHashMap(); - unitProp.put("type", "string"); - unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); - - Map properties = new LinkedHashMap(); - properties.put("location", locationProp); - properties.put("unit", unitProp); - - Map parameters = new HashMap(); - parameters.put("type", BinaryData.fromObject("object")); - parameters.put("properties", BinaryData.fromObject(properties)); - parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); - parameters.put("additionalProperties", BinaryData.fromObject(false)); - - FunctionTool tool = new FunctionTool("get_weather", parameters, true) - .setDescription("Get the current weather in a given location"); - - // Create the agent definition with Function tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can get weather information. " - + "When asked about the weather, use the get_weather function to retrieve weather data.") - .setTools(Collections.singletonList(tool)); - - agent = agentsClient.createAgentVersion("function-call-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What's the weather like in Seattle?")); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("What's the weather like in Seattle?") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -112,10 +117,7 @@ public static void main(String[] args) { } } } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java index 6468833a74f6b..277dead2efdb2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ImageGenTool; import com.azure.ai.agents.models.ImageGenToolModel; import com.azure.ai.agents.models.ImageGenToolQuality; @@ -19,8 +15,15 @@ import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Image Generation tool @@ -44,9 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create image generation tool with model, quality, and size ImageGenTool imageGenTool = new ImageGenTool() @@ -58,30 +58,27 @@ public static void main(String[] args) { .setInstructions("You are a creative assistant that can generate images based on descriptions.") .setTools(Collections.singletonList(imageGenTool)); - agentsAsyncClient.createAgentVersion("image-gen-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Generate an image of a sunset over a mountain range")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "image-gen-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Generate an image of a sunset over a mountain range") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java index dbff886b33131..a3d2f17799fbb 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ImageGenTool; import com.azure.ai.agents.models.ImageGenToolModel; import com.azure.ai.agents.models.ImageGenToolQuality; @@ -18,6 +14,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -43,7 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_image_generation // Create image generation tool with model, quality, and size @@ -58,18 +61,21 @@ public static void main(String[] args) { .setInstructions("You are a creative assistant that can generate images based on descriptions.") .setTools(Collections.singletonList(imageGenTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("image-gen-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "image-gen-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Generate an image of a sunset over a mountain range")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Generate an image of a sunset over a mountain range") + .build()); // The response output may include image_generation_call items with base64-encoded image data. // This sample prints the response status and the number of output items; image extraction @@ -77,8 +83,7 @@ public static void main(String[] args) { System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Output items: " + response.output().size()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java index 9a6d47002b0cf..379ad379b4df7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java @@ -5,25 +5,28 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with a Model Context Protocol (MCP) tool @@ -48,9 +51,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create an MCP tool that connects to a remote MCP server // Uses gitmcp.io to expose a GitHub repository as an MCP-compatible server @@ -63,83 +63,77 @@ public static void main(String[] args) { + "Use the available MCP tools to answer questions and perform tasks.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("mcp-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Please summarize the Azure REST API specifications Readme")); - }) - .flatMap(response -> { - AgentVersionDetails agent = agentRef.get(); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - // Process MCP approval requests - List approvals = new ArrayList(); - for (ResponseOutputItem item : response.output()) { - if (item.isMcpApprovalRequest()) { - ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); - System.out.printf("MCP approval requested: server=%s, id=%s%n", - request.serverLabel(), request.id()); - - approvals.add(ResponseInputItem.ofMcpApprovalResponse( - ResponseInputItem.McpApprovalResponse.builder() - .approvalRequestId(request.id()) - .approve(true) - .build())); - } - } - - if (!approvals.isEmpty()) { - System.out.println("Sending " + approvals.size() + " approval(s)..."); - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .inputOfResponse(approvals) - .previousResponseId(response.id())); - } - - return Mono.just(response); - }) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); + String agentName = "mcp-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Please summarize the Azure REST API specifications Readme") + .build())) + .flatMap(response -> { + // Process MCP approval requests + List approvals = new ArrayList(); + for (ResponseOutputItem item : response.output()) { + if (item.isMcpApprovalRequest()) { + ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); + System.out.printf("MCP approval requested: server=%s, id=%s%n", + request.serverLabel(), request.id()); + + approvals.add(ResponseInputItem.ofMcpApprovalResponse( + ResponseInputItem.McpApprovalResponse.builder() + .approvalRequestId(request.id()) + .approve(true) + .build())); + } + } + + if (!approvals.isEmpty()) { + System.out.println("Sending " + approvals.size() + " approval(s)..."); + return Mono.fromFuture(openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build())); + } + + return Mono.just(response); + }) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); + }); + } + + if (outputItem.mcpCall().isPresent()) { + ResponseOutputItem.McpCall mcpCall = outputItem.mcpCall().get(); + System.out.println("\n--- MCP Tool Call ---"); + System.out.println("Call ID: " + mcpCall.id()); + System.out.println("Server Label: " + mcpCall.serverLabel()); + System.out.println("Tool Name: " + mcpCall.name()); + System.out.println("Arguments: " + mcpCall.arguments()); + mcpCall.status().ifPresent(status -> System.out.println("Status: " + status)); + mcpCall.output().ifPresent(output -> System.out.println("Output: " + output)); + mcpCall.error().ifPresent(error -> System.out.println("Error: " + error)); + } + } }); - } - - if (outputItem.mcpCall().isPresent()) { - ResponseOutputItem.McpCall mcpCall = outputItem.mcpCall().get(); - System.out.println("\n--- MCP Tool Call ---"); - System.out.println("Call ID: " + mcpCall.id()); - System.out.println("Server Label: " + mcpCall.serverLabel()); - System.out.println("Tool Name: " + mcpCall.name()); - System.out.println("Arguments: " + mcpCall.arguments()); - mcpCall.status().ifPresent(status -> System.out.println("Status: " + status)); - mcpCall.output().ifPresent(output -> System.out.println("Output: " + output)); - mcpCall.error().ifPresent(error -> System.out.println("Error: " + error)); - } - } - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java index 61e36a8fbc532..643a712675520 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java @@ -5,19 +5,23 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.ArrayList; import java.util.Collections; @@ -46,35 +50,36 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - - AgentVersionDetails agent = null; + // Create an MCP tool that connects to a remote MCP server + // BEGIN: com.azure.ai.agents.built_in_mcp + // Uses gitmcp.io to expose a GitHub repository as an MCP-compatible server + McpTool tool = new McpTool("api-specs") + .setServerUrl("https://gitmcp.io/Azure/azure-rest-api-specs") + .setRequireApproval("always"); + // END: com.azure.ai.agents.built_in_mcp + + // Create the agent definition with MCP tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful agent that can use MCP tools to assist users. " + + "Use the available MCP tools to answer questions and perform tasks.") + .setTools(Collections.singletonList(tool)); + + String agentName = "mcp-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create an MCP tool that connects to a remote MCP server - // BEGIN: com.azure.ai.agents.built_in_mcp - // Uses gitmcp.io to expose a GitHub repository as an MCP-compatible server - McpTool tool = new McpTool("api-specs") - .setServerUrl("https://gitmcp.io/Azure/azure-rest-api-specs") - .setRequireApproval("always"); - // END: com.azure.ai.agents.built_in_mcp - - // Create the agent definition with MCP tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful agent that can use MCP tools to assist users. " - + "Use the available MCP tools to answer questions and perform tasks.") - .setTools(Collections.singletonList(tool)); - - agent = agentsClient.createAgentVersion("mcp-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Please summarize the Azure REST API specifications Readme")); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Please summarize the Azure REST API specifications Readme") + .build()); // Process MCP approval requests — the server requires approval before executing tools List approvals = new ArrayList(); @@ -95,11 +100,10 @@ public static void main(String[] args) { // If approvals were needed, send them back and get the final response if (!approvals.isEmpty()) { System.out.println("Sending " + approvals.size() + " approval(s)..."); - response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .inputOfResponse(approvals) - .previousResponseId(response.id())); + response = openAIClient.responses().create(ResponseCreateParams.builder() + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build()); } // Process and display the final response @@ -126,10 +130,7 @@ public static void main(String[] args) { } } } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java index e8d8ba25e2f9c..351542ba643e6 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java @@ -5,24 +5,27 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an MCP tool @@ -46,9 +49,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); McpTool mcpTool = new McpTool("api-specs") .setServerUrl("https://api.githubcopilot.com/mcp") @@ -59,62 +59,54 @@ public static void main(String[] args) { .setInstructions("Use MCP tools as needed") .setTools(Collections.singletonList(mcpTool)); - agentsAsyncClient.createAgentVersion("mcp-connection-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What is my username in GitHub profile?")); - }) - .flatMap(response -> { - AgentVersionDetails agent = agentRef.get(); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - // Process MCP approval requests - List approvals = new ArrayList<>(); - for (ResponseOutputItem item : response.output()) { - if (item.isMcpApprovalRequest()) { - ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); - System.out.printf("MCP approval requested: server=%s, id=%s%n", - request.serverLabel(), request.id()); - - approvals.add(ResponseInputItem.ofMcpApprovalResponse( - ResponseInputItem.McpApprovalResponse.builder() - .approvalRequestId(request.id()) - .approve(true) - .build())); - } - } - - if (!approvals.isEmpty()) { - System.out.println("Sending " + approvals.size() + " approval(s)..."); - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .inputOfResponse(approvals) - .previousResponseId(response.id())); - } - - return Mono.just(response); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "mcp-connection-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("What is my username in GitHub profile?") + .build())) + .flatMap(response -> { + // Process MCP approval requests + List approvals = new ArrayList<>(); + for (ResponseOutputItem item : response.output()) { + if (item.isMcpApprovalRequest()) { + ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); + System.out.printf("MCP approval requested: server=%s, id=%s%n", + request.serverLabel(), request.id()); + + approvals.add(ResponseInputItem.ofMcpApprovalResponse( + ResponseInputItem.McpApprovalResponse.builder() + .approvalRequestId(request.id()) + .approve(true) + .build())); + } + } + + if (!approvals.isEmpty()) { + System.out.println("Sending " + approvals.size() + " approval(s)..."); + return Mono.fromFuture(openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build())); + } + + return Mono.just(response); + }) + .doOnNext(response -> System.out.println("Response: " + response.output())); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java index c4efb7ecdd6c0..1544d1a1d6874 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java @@ -5,20 +5,24 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import com.openai.services.blocking.ConversationService; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.ArrayList; import java.util.Collections; @@ -50,7 +54,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); // BEGIN: com.azure.ai.agents.define_mcp_with_connection @@ -66,22 +69,26 @@ public static void main(String[] args) { .setInstructions("Use MCP tools as needed") .setTools(Collections.singletonList(mcpTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("mcp-connection-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "mcp-connection-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); // Create a conversation for context Conversation conversation = conversationService.create(); // Send initial request that triggers the MCP tool - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(conversation.id()) - .input("What is my username in GitHub profile?")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .input("What is my username in GitHub profile?") + .build()); // Process MCP approval requests: approve each one so the agent can proceed List approvals = new ArrayList<>(); @@ -103,20 +110,18 @@ public static void main(String[] args) { System.out.println("Sending " + approvals.size() + " approval(s)..."); // Send approvals back to continue the agent's work - Response followUp = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(conversation.id()) - .inputOfResponse(approvals) - .previousResponseId(response.id())); + Response followUp = openAIClient.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build()); System.out.println("Response: " + followUp.output()); } else { System.out.println("Response: " + response.output()); } } finally { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java index 1abd7896df4f7..c3fb4798fe8ab 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java @@ -6,18 +6,21 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.BetaMemoryStoresClient; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.MemorySearchPreviewTool; import com.azure.ai.agents.models.MemoryStoreDefaultDefinition; import com.azure.ai.agents.models.MemoryStoreDefaultOptions; import com.azure.ai.agents.models.MemoryStoreDetails; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.services.async.ConversationServiceAsync; @@ -53,7 +56,6 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); ConversationServiceAsync conversationServiceAsync = builder.buildOpenAIAsyncClient().conversations(); // Memory store operations use sync client for setup/teardown BetaMemoryStoresClient memoryStoresClient = builder.beta().buildBetaMemoryStoresClient(); @@ -61,7 +63,6 @@ public static void main(String[] args) throws Exception { String memoryStoreName = "my_memory_store"; String scope = "user_123"; - AtomicReference agentRef = new AtomicReference<>(); AtomicReference firstConvRef = new AtomicReference<>(); AtomicReference secondConvRef = new AtomicReference<>(); @@ -85,44 +86,44 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("memory-search-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - // First conversation: teach a preference - return Mono.fromFuture(conversationServiceAsync.create()) - .flatMap(conv -> { - firstConvRef.set(conv.id()); - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(conv.id()) - .input("I prefer dark roast coffee")); - }); - }) - .doOnNext(response -> System.out.println("First response received")) - .delayElement(Duration.ofSeconds(MEMORY_WRITE_DELAY_SECONDS)) - .flatMap(ignored -> { - AgentVersionDetails agent = agentRef.get(); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - // Second conversation: test memory recall - return Mono.fromFuture(conversationServiceAsync.create()) - .flatMap(conv -> { - secondConvRef.set(conv.id()); - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .conversation(conv.id()) - .input("Please order my usual coffee")); - }); - }) - .doOnNext(response -> System.out.println("Response: " + response.output())) + String agentName = "memory-search-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + + // First conversation: teach a preference + return Mono.fromFuture(conversationServiceAsync.create()) + .flatMap(conv -> { + firstConvRef.set(conv.id()); + return Mono.fromFuture(openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .conversation(conv.id()) + .input("I prefer dark roast coffee") + .build())); + }) + .doOnNext(response -> System.out.println("First response received")) + .delayElement(Duration.ofSeconds(MEMORY_WRITE_DELAY_SECONDS)) + .flatMap(ignored -> Mono.fromFuture(conversationServiceAsync.create()) + .flatMap(conv -> { + secondConvRef.set(conv.id()); + return Mono.fromFuture(openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .conversation(conv.id()) + .input("Please order my usual coffee") + .build())); + })) + .doOnNext(response -> System.out.println("Response: " + response.output())); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doFinally(signal -> { // Cleanup — await conversation deletes before proceeding try { @@ -137,11 +138,6 @@ public static void main(String[] args) throws Exception { } catch (Exception ignored) { // best-effort } - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()).block(); - System.out.println("Agent deleted"); - } try { memoryStoresClient.deleteMemoryStore(memoryStoreName); System.out.println("Memory store deleted"); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java index 051faf45c1c81..a8dcbcc18588a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java @@ -5,19 +5,23 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.BetaMemoryStoresClient; +import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.MemorySearchPreviewTool; import com.azure.ai.agents.models.MemoryStoreDefaultDefinition; import com.azure.ai.agents.models.MemoryStoreDefaultOptions; import com.azure.ai.agents.models.MemoryStoreDetails; -import com.azure.ai.agents.BetaMemoryStoresClient; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; @@ -54,11 +58,9 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); BetaMemoryStoresClient memoryStoresClient = builder.beta().buildBetaMemoryStoresClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); - ResponsesClient responsesClient = builder.buildResponsesClient(); String memoryStoreName = "my_memory_store"; String scope = "user_123"; - AgentVersionDetails agent = null; String firstConversationId = null; String followUpConversationId = null; @@ -85,49 +87,52 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - agent = agentsClient.createAgentVersion("memory-search-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + // Create the agent version and point the agent endpoint at the new version. + String agentName = "memory-search-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + try { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - // First conversation: teach the agent a preference - Conversation conversation = conversationService.create(); - firstConversationId = conversation.id(); - System.out.println("Created conversation (id: " + firstConversationId + ")"); + // First conversation: teach the agent a preference + Conversation conversation = conversationService.create(); + firstConversationId = conversation.id(); + System.out.println("Created conversation (id: " + firstConversationId + ")"); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() + Response response = openAIClient.responses().create(ResponseCreateParams.builder() .conversation(firstConversationId) - .input("I prefer dark roast coffee")); - System.out.println("Response: " + getResponseText(response)); + .input("I prefer dark roast coffee") + .build()); + System.out.println("Response: " + getResponseText(response)); - // Wait for memories to be extracted and stored - System.out.println("Waiting for memories to be stored..."); - TimeUnit.SECONDS.sleep(MEMORY_WRITE_DELAY_SECONDS); + // Wait for memories to be extracted and stored + System.out.println("Waiting for memories to be stored..."); + TimeUnit.SECONDS.sleep(MEMORY_WRITE_DELAY_SECONDS); - // Second conversation: test memory recall - Conversation newConversation = conversationService.create(); - followUpConversationId = newConversation.id(); - System.out.println("Created new conversation (id: " + followUpConversationId + ")"); + // Second conversation: test memory recall + Conversation newConversation = conversationService.create(); + followUpConversationId = newConversation.id(); + System.out.println("Created new conversation (id: " + followUpConversationId + ")"); - Response followUpResponse = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() + Response followUpResponse = openAIClient.responses().create(ResponseCreateParams.builder() .conversation(followUpConversationId) - .input("Please order my usual coffee")); - System.out.println("Response: " + getResponseText(followUpResponse)); + .input("Please order my usual coffee") + .build()); + System.out.println("Response: " + getResponseText(followUpResponse)); + } finally { + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Sleep interrupted", e); } finally { deleteConversationQuietly(conversationService, firstConversationId); deleteConversationQuietly(conversationService, followUpConversationId); - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } deleteMemoryStoreQuietly(memoryStoresClient, memoryStoreName); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java index e2c6b049fd60e..b0d8058f1b564 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java @@ -5,11 +5,7 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; import com.azure.ai.agents.SampleUtils; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiAnonymousAuthDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiTool; @@ -19,11 +15,18 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an OpenAPI tool @@ -45,9 +48,6 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); Map spec = OpenApiFunctionDefinition.readSpecFromFile( SampleUtils.getResourcePath("assets/httpbin_openapi.json")); @@ -61,30 +61,27 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant. Use the OpenAPI tool when asked to call an API.") .setTools(Collections.singletonList(openApiTool)); - agentsAsyncClient.createAgentVersion("openapi-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Call the API and tell me what it returns.")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "openapi-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Call the API and tell me what it returns.") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java index f37d2b4e947fc..31c24629070b8 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java @@ -5,11 +5,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; import com.azure.ai.agents.SampleUtils; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiAnonymousAuthDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiTool; @@ -17,14 +13,23 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.conversations.items.ItemCreateParams; import com.openai.models.responses.EasyInputMessage; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; +import java.util.Collections; import java.util.Map; /** @@ -49,7 +54,6 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); @@ -67,30 +71,33 @@ public static void main(String[] args) throws Exception { .setInstructions("Use the OpenAPI tool for HTTP request metadata.") .setTools(Arrays.asList(new OpenApiTool(toolDefinition))); - AgentVersionDetails agentVersion = agentsClient.createAgentVersion("openapi-agent", agentDefinition); - System.out.println("Agent: " + agentVersion.getName() + ", version: " + agentVersion.getVersion()); - - // Create a conversation and add a user message - Conversation conversation = conversationService.create(); - conversationService.items().create( - ItemCreateParams.builder() - .conversationId(conversation.id()) - .addItem(EasyInputMessage.builder() - .role(EasyInputMessage.Role.USER) - .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") - .build()) - .build()); - + String agentName = "openapi-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - AgentReference agentReference = new AgentReference(agentVersion.getName()) - .setVersion(agentVersion.getVersion()); - - ResponseCreateParams.Builder options = ResponseCreateParams.builder() - .maxOutputTokens(300L); - - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - options.conversation(conversation.id())); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + + // Create a conversation and add a user message + Conversation conversation = conversationService.create(); + conversationService.items().create( + ItemCreateParams.builder() + .conversationId(conversation.id()) + .addItem(EasyInputMessage.builder() + .role(EasyInputMessage.Role.USER) + .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") + .build()) + .build()); + + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .maxOutputTokens(300L) + .conversation(conversation.id()) + .build()); String text = response.output().stream() .filter(item -> item.isMessage()) @@ -104,8 +111,7 @@ public static void main(String[] args) throws Exception { System.out.println("Status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Response: " + text); } finally { - agentsClient.deleteAgentVersion(agentVersion.getName(), agentVersion.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java index 947b842665ee3..9e0367c29300a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java @@ -5,11 +5,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; import com.azure.ai.agents.SampleUtils; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiAnonymousAuthDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiTool; @@ -17,14 +13,23 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.conversations.Conversation; import com.openai.models.conversations.items.ItemCreateParams; import com.openai.models.responses.EasyInputMessage; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; +import java.util.Collections; import java.util.Map; /** @@ -49,7 +54,6 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); @@ -70,30 +74,33 @@ public static void main(String[] args) throws Exception { .setInstructions("Use the OpenAPI tool for HTTP request metadata.") .setTools(Arrays.asList(tool)); - AgentVersionDetails agentVersion = agentsClient.createAgentVersion("openapi-agent", agentDefinition); - System.out.println("Agent: " + agentVersion.getName() + ", version: " + agentVersion.getVersion()); - - // Create a conversation and add a user message - Conversation conversation = conversationService.create(); - conversationService.items().create( - ItemCreateParams.builder() - .conversationId(conversation.id()) - .addItem(EasyInputMessage.builder() - .role(EasyInputMessage.Role.USER) - .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") - .build()) - .build()); - + String agentName = "openapi-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - AgentReference agentReference = new AgentReference(agentVersion.getName()) - .setVersion(agentVersion.getVersion()); - - ResponseCreateParams.Builder options = ResponseCreateParams.builder() - .maxOutputTokens(300L); - - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - options.conversation(conversation.id())); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + + // Create a conversation and add a user message + Conversation conversation = conversationService.create(); + conversationService.items().create( + ItemCreateParams.builder() + .conversationId(conversation.id()) + .addItem(EasyInputMessage.builder() + .role(EasyInputMessage.Role.USER) + .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") + .build()) + .build()); + + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .maxOutputTokens(300L) + .conversation(conversation.id()) + .build()); String text = response.output().stream() .filter(item -> item.isMessage()) @@ -107,8 +114,7 @@ public static void main(String[] args) throws Exception { System.out.println("Status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Response: " + text); } finally { - agentsClient.deleteAgentVersion(agentVersion.getName(), agentVersion.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java index 6d1ae7e2a56fb..2e935da1457fa 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java @@ -5,11 +5,7 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; import com.azure.ai.agents.SampleUtils; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiProjectConnectionAuthDetails; import com.azure.ai.agents.models.OpenApiProjectConnectionSecurityScheme; @@ -20,11 +16,18 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an OpenAPI tool @@ -48,9 +51,6 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); Map spec = OpenApiFunctionDefinition.readSpecFromFile( SampleUtils.getResourcePath("assets/httpbin_openapi.json")); @@ -67,30 +67,27 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(openApiTool)); - agentsAsyncClient.createAgentVersion("openapi-connection-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Call the API and summarize the returned URL and origin.")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "openapi-connection-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Call the API and summarize the returned URL and origin.") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java index 6d021ad4cf572..a3af2614604cf 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java @@ -5,11 +5,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; import com.azure.ai.agents.SampleUtils; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiProjectConnectionAuthDetails; import com.azure.ai.agents.models.OpenApiProjectConnectionSecurityScheme; @@ -20,6 +16,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Map; @@ -52,7 +56,6 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // Load the OpenAPI spec from a JSON file Map spec = OpenApiFunctionDefinition.readSpecFromFile( @@ -74,22 +77,25 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(openApiTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("openapi-connection-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "openapi-connection-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Call the API and summarize the returned URL and origin.")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Call the API and summarize the returned URL and origin.") + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java index 0ef03e7dae7ad..e20812c62603e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.SharepointGroundingToolParameters; import com.azure.ai.agents.models.SharepointPreviewTool; @@ -19,8 +15,15 @@ import java.time.Duration; import java.util.Arrays; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the SharePoint Grounding tool @@ -44,9 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create SharePoint grounding tool with connection configuration SharepointPreviewTool sharepointTool = new SharepointPreviewTool( @@ -60,30 +60,27 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can search through SharePoint documents.") .setTools(Collections.singletonList(sharepointTool)); - agentsAsyncClient.createAgentVersion("sharepoint-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Find the latest project documentation in SharePoint")); - }) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + String agentName = "sharepoint-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("Find the latest project documentation in SharePoint") + .build())) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }); + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java index 97e064286024a..6efbc92b29b40 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.SharepointGroundingToolParameters; import com.azure.ai.agents.models.SharepointPreviewTool; @@ -17,6 +13,14 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Arrays; @@ -43,7 +47,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_sharepoint // Create SharePoint grounding tool with connection configuration @@ -60,23 +63,25 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can search through SharePoint documents.") .setTools(Collections.singletonList(sharepointTool)); - AgentVersionDetails agent = agentsClient.createAgentVersion("sharepoint-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - + String agentName = "sharepoint-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - // Create a response - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Find the latest project documentation in SharePoint")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("Find the latest project documentation in SharePoint") + .build()); System.out.println("Response: " + response.output()); } finally { - // Clean up - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java index 7b91c54a49f4a..760e786e27a28 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WebSearchPreviewTool; import com.azure.core.util.Configuration; @@ -17,10 +13,17 @@ import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; +import com.openai.client.OpenAIClientAsync; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; -import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create an agent with the Web Search tool @@ -42,9 +45,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); - - AtomicReference agentRef = new AtomicReference<>(); // Create a WebSearchPreviewTool WebSearchPreviewTool tool = new WebSearchPreviewTool(); @@ -54,39 +54,36 @@ public static void main(String[] args) { + "When asked to find information, use the web search tool to gather relevant data.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("web-search-agent", agentDefinition) - .flatMap(agent -> { - agentRef.set(agent); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What are the latest trends in renewable energy?")); - }) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); + String agentName = "web-search-agent"; + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + .input("What are the latest trends in renewable energy?") + .build())) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); + }); + } + } }); - } - } - }) - .then(Mono.defer(() -> { - AgentVersionDetails agent = agentRef.get(); - if (agent != null) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(v -> System.out.println("Agent deleted")); - } - return Mono.empty(); - })) + }, + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(30)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java index 294203ca1d7bb..0e5caf6ec7044 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java @@ -5,18 +5,22 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WebSearchPreviewTool; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -40,32 +44,33 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - AgentVersionDetails agent = null; + // BEGIN: com.azure.ai.agents.define_web_search + // Create a WebSearchPreviewTool + WebSearchPreviewTool tool = new WebSearchPreviewTool(); + // END: com.azure.ai.agents.define_web_search - try { - // BEGIN: com.azure.ai.agents.define_web_search - // Create a WebSearchPreviewTool - WebSearchPreviewTool tool = new WebSearchPreviewTool(); - // END: com.azure.ai.agents.define_web_search + // Create the agent definition with Web Search tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can perform web searches to find information. " + + "When asked to find information, use the web search tool to gather relevant data.") + .setTools(Collections.singletonList(tool)); - // Create the agent definition with Web Search tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can perform web searches to find information. " - + "When asked to find information, use the web search tool to gather relevant data.") - .setTools(Collections.singletonList(tool)); + String agentName = "web-search-agent"; + AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + try { + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - agent = agentsClient.createAgentVersion("web-search-agent", agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What are the latest trends in renewable energy?")); + Response response = openAIClient.responses().create(ResponseCreateParams.builder() + .input("What are the latest trends in renewable energy?") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -79,10 +84,7 @@ public static void main(String[] args) { } } } finally { - if (agent != null) { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); - } + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java index 6dbcc59ce2e25..5d213caecba76 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java @@ -5,19 +5,23 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.AzureCreateResponseOptions; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WorkIqPreviewTool; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputMessage; import com.openai.models.responses.ToolChoiceOptions; import reactor.core.publisher.Mono; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; @@ -53,7 +57,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); WorkIqPreviewTool workIqTool = new WorkIqPreviewTool(workIqConnectionId); @@ -63,40 +66,34 @@ public static void main(String[] args) { + "Teams messages, and other Microsoft 365 content.") .setTools(Collections.singletonList(workIqTool)); - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> Mono.usingWhen( - Mono.just(agent), - createdAgent -> { - System.out.printf("Agent created: %s (version %s)%n", - createdAgent.getName(), createdAgent.getVersion()); - - AgentReference agentReference = new AgentReference(createdAgent.getName()) - .setVersion(createdAgent.getVersion()); - - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() + Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, + new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) + .thenReturn(agent)), + agent -> { + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agentName); + return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) - .input(userInput)) + .input(userInput) + .build())) .doOnNext(response -> { System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Agent response: " + getResponseText(response)); }); }, - createdAgent -> deleteAgentVersion(agentsAsyncClient, createdAgent), - (createdAgent, error) -> deleteAgentVersion(agentsAsyncClient, createdAgent), - createdAgent -> deleteAgentVersion(agentsAsyncClient, createdAgent))) + agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); } - private static Mono deleteAgentVersion(AgentsAsyncClient agentsAsyncClient, AgentVersionDetails agent) { - return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) - .doOnSuccess(unused -> System.out.println("Agent deleted")); - } - private static String getResponseText(Response response) { if (response == null || response.output().isEmpty()) { return ""; diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java index da82b461f4d9f..b6007e61beaa4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java @@ -5,10 +5,6 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.AzureCreateResponseOptions; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WorkIqPreviewTool; import com.azure.core.util.Configuration; @@ -17,6 +13,14 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputMessage; import com.openai.models.responses.ToolChoiceOptions; +import com.openai.client.OpenAIClient; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -51,7 +55,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); // BEGIN: com.azure.ai.agents.define_work_iq // Create a Work IQ tool with a fully qualified project connection resource ID @@ -65,23 +68,25 @@ public static void main(String[] args) { .setTools(Collections.singletonList(workIqTool)); AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - try { - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( + new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() + Response response = openAIClient.responses().create(ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) - .input(userInput)); + .input(userInput) + .build()); System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Agent response: " + getResponseText(response)); } finally { - agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); - System.out.println("Agent deleted"); + agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } From 87cdaf1ce0905a0c7c429d1f5c2481f820e5d25e Mon Sep 17 00:00:00 2001 From: kaylieee Date: Thu, 3 Sep 2026 15:41:11 -0700 Subject: [PATCH 02/17] simplify async --- sdk/ai/azure-ai-agents/README.md | 27 +++++------------ .../CodeInterpreterStreamingAsync.java | 25 ++++------------ .../streaming/FunctionCallStreamingAsync.java | 26 ++++------------ .../streaming/SimpleStreamingAsync.java | 30 +++++-------------- 4 files changed, 26 insertions(+), 82 deletions(-) diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index a405f4ea71ecd..2f2243eacffd6 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -810,27 +810,14 @@ The asynchronous streaming methods return `Flux`, integrati ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); // Stream response asynchronously - text is printed as each chunk arrives -AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( - ResponseCreateParams.builder() +return Mono.fromFuture(openAIAsyncClient.responses() + .createStreaming(ResponseCreateParams.builder() .input("Tell me a short story about a brave explorer.") - .build()); - -stream.subscribe(new AsyncStreamResponse.Handler() { - @Override - public void onNext(ResponseStreamEvent event) { - responseAccumulator.accumulate(event); - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - } - - @Override - public void onComplete(java.util.Optional error) { - // No-op: onCompleteFuture below signals completion. - } -}); - -return Mono.fromFuture(stream.onCompleteFuture()) - .doFinally(signal -> stream.close()) + .build()) + .subscribe(event -> responseAccumulator.accumulate(event) + .outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta()))) + .onCompleteFuture()) .doOnSuccess(unused -> { System.out.println(); // newline after streamed text diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java index 12cad1775a19e..08f1c7ebeabc4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java @@ -10,11 +10,9 @@ import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; -import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; @@ -77,14 +75,11 @@ public static void main(String[] args) { // Stream response asynchronously with Code Interpreter ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( - ResponseCreateParams.builder() + return Mono.fromFuture(openAIAsyncClient.responses() + .createStreaming(ResponseCreateParams.builder() .input("Calculate the first 10 prime numbers using Python.") - .build()); - - stream.subscribe(new AsyncStreamResponse.Handler() { - @Override - public void onNext(ResponseStreamEvent event) { + .build()) + .subscribe(event -> { responseAccumulator.accumulate(event); // Print text deltas as they arrive event.outputTextDelta() @@ -96,16 +91,8 @@ public void onNext(ResponseStreamEvent event) { .ifPresent(e -> System.out.print(e.delta())); event.codeInterpreterCallCompleted() .ifPresent(e -> System.out.println("\n[Code interpreter completed]")); - } - - @Override - public void onComplete(java.util.Optional error) { - // No-op: onCompleteFuture below signals completion. - } - }); - - return Mono.fromFuture(stream.onCompleteFuture()) - .doFinally(signal -> stream.close()) + }) + .onCompleteFuture()) .doOnSuccess(unused -> { System.out.println(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java index a4fa49d0b9cc9..ff85aeb39e596 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java @@ -11,15 +11,12 @@ import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; -import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; -import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.ProtocolConfiguration; import com.azure.ai.agents.models.ResponsesProtocolConfiguration; @@ -102,14 +99,11 @@ public static void main(String[] args) { // Stream response asynchronously with function tool ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( - ResponseCreateParams.builder() + return Mono.fromFuture(openAIAsyncClient.responses() + .createStreaming(ResponseCreateParams.builder() .input("What's the weather like in Seattle?") - .build()); - - stream.subscribe(new AsyncStreamResponse.Handler() { - @Override - public void onNext(ResponseStreamEvent event) { + .build()) + .subscribe(event -> { responseAccumulator.accumulate(event); // Print text deltas as they arrive event.outputTextDelta() @@ -117,16 +111,8 @@ public void onNext(ResponseStreamEvent event) { // Print function call argument deltas as they arrive event.functionCallArgumentsDelta() .ifPresent(argEvent -> System.out.print(argEvent.delta())); - } - - @Override - public void onComplete(java.util.Optional error) { - // No-op: onCompleteFuture below signals completion. - } - }); - - return Mono.fromFuture(stream.onCompleteFuture()) - .doFinally(signal -> stream.close()) + }) + .onCompleteFuture()) .doOnSuccess(unused -> { System.out.println(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java index a4dab798949f1..371868bb54faf 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java @@ -9,14 +9,11 @@ import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; -import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.ProtocolConfiguration; import com.azure.ai.agents.models.ResponsesProtocolConfiguration; @@ -71,27 +68,14 @@ public static void main(String[] args) { ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); // Stream response asynchronously - text is printed as each chunk arrives - AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( - ResponseCreateParams.builder() + return Mono.fromFuture(openAIAsyncClient.responses() + .createStreaming(ResponseCreateParams.builder() .input("Tell me a short story about a brave explorer.") - .build()); - - stream.subscribe(new AsyncStreamResponse.Handler() { - @Override - public void onNext(ResponseStreamEvent event) { - responseAccumulator.accumulate(event); - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - } - - @Override - public void onComplete(java.util.Optional error) { - // No-op: onCompleteFuture below signals completion. - } - }); - - return Mono.fromFuture(stream.onCompleteFuture()) - .doFinally(signal -> stream.close()) + .build()) + .subscribe(event -> responseAccumulator.accumulate(event) + .outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta()))) + .onCompleteFuture()) .doOnSuccess(unused -> { System.out.println(); // newline after streamed text From 15ffd5771fb116ed297a8a7b569daf1ef05bb0d9 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 11:16:47 -0700 Subject: [PATCH 03/17] fix imports, add util helper --- .../CreateResponseWithConversation.java | 60 ++++---- .../azure/ai/agents/MemorySearchAgent.java | 82 +++++----- .../ai/agents/MultipleAgentsConversation.java | 118 +++++++-------- .../java/com/azure/ai/agents/SampleUtils.java | 44 ++++++ .../CodeInterpreterStreamingAsync.java | 1 - .../CodeInterpreterStreamingSync.java | 57 +++---- .../streaming/FunctionCallStreamingSync.java | 95 ++++++------ .../agents/streaming/SimpleStreamingSync.java | 43 +++--- .../ai/agents/tools/AgentToAgentAsync.java | 56 +++---- .../ai/agents/tools/AgentToAgentSync.java | 35 ++--- .../ai/agents/tools/AzureAISearchAsync.java | 57 ++++--- .../ai/agents/tools/AzureAISearchSync.java | 35 ++--- .../ai/agents/tools/AzureFunctionAsync.java | 52 ++++--- .../ai/agents/tools/AzureFunctionSync.java | 36 ++--- .../agents/tools/BingCustomSearchAsync.java | 56 +++---- .../ai/agents/tools/BingCustomSearchSync.java | 34 ++--- .../ai/agents/tools/BingGroundingAsync.java | 56 +++---- .../ai/agents/tools/BingGroundingSync.java | 35 ++--- .../agents/tools/BrowserAutomationAsync.java | 56 +++---- .../agents/tools/BrowserAutomationSync.java | 35 ++--- .../ai/agents/tools/CodeInterpreterAsync.java | 90 ++++++----- .../ai/agents/tools/CodeInterpreterSync.java | 55 ++++--- .../ai/agents/tools/ComputerUseAsync.java | 87 +++++------ .../ai/agents/tools/ComputerUseSync.java | 79 +++++----- .../tools/CustomCodeInterpreterAsync.java | 56 +++---- .../tools/CustomCodeInterpreterSync.java | 37 ++--- .../azure/ai/agents/tools/FabricAsync.java | 56 +++---- .../azure/ai/agents/tools/FabricIQAsync.java | 53 ++++--- .../azure/ai/agents/tools/FabricIQSync.java | 31 ++-- .../com/azure/ai/agents/tools/FabricSync.java | 35 ++--- .../ai/agents/tools/FunctionCallAsync.java | 90 +++++------ .../ai/agents/tools/FunctionCallSync.java | 93 ++++++------ .../ai/agents/tools/ImageGenerationAsync.java | 56 +++---- .../ai/agents/tools/ImageGenerationSync.java | 35 ++--- .../com/azure/ai/agents/tools/McpAsync.java | 143 +++++++++--------- .../com/azure/ai/agents/tools/McpSync.java | 78 +++++----- .../agents/tools/McpWithConnectionAsync.java | 101 +++++++------ .../agents/tools/McpWithConnectionSync.java | 47 +++--- .../ai/agents/tools/MemorySearchAsync.java | 83 +++++----- .../ai/agents/tools/MemorySearchSync.java | 64 ++++---- .../azure/ai/agents/tools/OpenApiAsync.java | 55 ++++--- .../azure/ai/agents/tools/OpenApiSample.java | 59 +++----- .../azure/ai/agents/tools/OpenApiSync.java | 59 +++----- .../tools/OpenApiWithConnectionAsync.java | 55 ++++--- .../tools/OpenApiWithConnectionSync.java | 33 ++-- .../tools/SharePointGroundingAsync.java | 56 +++---- .../agents/tools/SharePointGroundingSync.java | 35 ++--- .../azure/ai/agents/tools/WebSearchAsync.java | 72 ++++----- .../azure/ai/agents/tools/WebSearchSync.java | 55 ++++--- .../azure/ai/agents/tools/WorkIQAsync.java | 44 +++--- .../com/azure/ai/agents/tools/WorkIQSync.java | 31 ++-- 51 files changed, 1446 insertions(+), 1520 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java index bcfd76133c5f4..87e5dad4dc630 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java @@ -24,8 +24,8 @@ import java.util.Collections; /** - * This sample demonstrates how to invoke the OpenAI Responses API against a Prompt Agent, - * routing all traffic through the agent's endpoint URL. + * This sample demonstrates how to to create a response with a conversation + * against an agent. */ public class CreateResponseWithConversation { public static void main(String[] args) { @@ -40,22 +40,25 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); ConversationService conversationService = builder.buildOpenAIClient().conversations(); - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant."); - - String agentName = "my-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - System.out.printf("Agent created (id: %s, version: %s)%n", agent.getId(), agent.getVersion()); + AgentVersionDetails agent = null; String conversationId = null; + try { - // Point the agent endpoint at the newly created version and enable the OpenAI Responses protocol. - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + // Create a prompt agent + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant."); + + agent = agentsClient.createAgentVersion("my-agent", agentDefinition); + System.out.printf("Agent created (id: %s, version: %s)\n", agent.getId(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // Create a conversation Conversation conversation = conversationService.create(); @@ -63,10 +66,11 @@ public static void main(String[] args) { System.out.println("Created conversation: " + conversationId); // Create a response using the conversation - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .conversation(conversationId) - .input("Hi, how can you help me?") - .build()); + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .conversation(conversationId) + .input("Hi, how can you help me?") + .build()); // Process and display the response System.out.println("\n=== Agent Response ==="); @@ -81,16 +85,20 @@ public static void main(String[] args) { } } System.out.println("Response ID: " + response.id()); + } catch (Exception e) { + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(); } finally { + // Cleanup conversation if (conversationId != null) { - try { - conversationService.delete(conversationId); - System.out.println("Conversation deleted."); - } catch (Exception ignored) { - // best-effort cleanup - } + conversationService.delete(conversationId); + System.out.println("Conversation deleted."); + } + // Cleanup agent + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted."); } - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java index 4a3e382a3268f..1b182360f80ed 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java @@ -54,6 +54,7 @@ public static void main(String[] args) { String description = "Example memory store for conversations"; String scope = "user_123"; + AgentVersionDetails agent = null; String firstConversationId = null; String followUpConversationId = null; @@ -74,47 +75,52 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - // Create the agent version and point the agent endpoint at the new version. - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - - Conversation conversation = conversationService.create(); - firstConversationId = conversation.id(); - System.out.println("Created conversation (id: " + firstConversationId + ")"); - - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .conversation(firstConversationId) - .input("I prefer dark roast coffee") - .build()); - System.out.println("Response output: " + getResponseText(response)); - - System.out.println("Waiting for memories to be stored..."); - sleepSeconds(MEMORY_WRITE_DELAY_SECONDS); - - Conversation newConversation = conversationService.create(); - followUpConversationId = newConversation.id(); - System.out.println("Created new conversation (id: " + followUpConversationId + ")"); - - Response followUpResponse = openAIClient.responses().create(ResponseCreateParams.builder() - .conversation(followUpConversationId) - .input("Please order my usual coffee") - .build()); - System.out.println("Response output: " + getResponseText(followUpResponse)); - - System.out.println("Sample completed successfully."); - } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); - } + agent = agentsClient.createAgentVersion(agentName, agentDefinition); + System.out.printf("Agent created (id: %s, version: %s)\n", agent.getId(), agent.getVersion()); + + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + + Conversation conversation = conversationService.create(); + firstConversationId = conversation.id(); + System.out.println("Created conversation (id: " + firstConversationId + ")"); + + + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .conversation(firstConversationId) + .input("I prefer dark roast coffee") + .build()); + System.out.println("Response output: " + getResponseText(response)); + + System.out.println("Waiting for memories to be stored..."); + sleepSeconds(MEMORY_WRITE_DELAY_SECONDS); + + Conversation newConversation = conversationService.create(); + followUpConversationId = newConversation.id(); + System.out.println("Created new conversation (id: " + followUpConversationId + ")"); + + Response followUpResponse = openAIClient.responses().create( + ResponseCreateParams.builder() + .conversation(followUpConversationId) + .input("Please order my usual coffee") + .build()); + System.out.println("Response output: " + getResponseText(followUpResponse)); + + System.out.println("Sample completed successfully."); } finally { deleteConversation(conversationService, firstConversationId); deleteConversation(conversationService, followUpConversationId); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } cleanupMemoryStore(memoryStoresClient, memoryStoreName); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java index fedadc52b539d..0632de7e5a071 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java @@ -25,11 +25,9 @@ import java.util.Collections; /** - * This sample shows how multiple agents can consume a centralized context source (conversation) and provide different - * responses based on it. + * This sample how multiple agents can consume a centralized context source (conversation) and provide different responses + * based on it. * - *

Each agent's identity is baked into its agent endpoint URL. To route requests to a specific agent, build an - * agent-scoped OpenAI client and call {@code responses().create(...)} through it.

*/ public class MultipleAgentsConversation { /** @@ -38,7 +36,7 @@ public class MultipleAgentsConversation { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); - + // Code sample for creating an agent AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .serviceVersion(AgentsServiceVersion.getLatest()) @@ -54,66 +52,60 @@ public static void main(String[] args) { printConversationItems(conversationsClient, conversation.id(), 2); - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model); - - // Create two agents and configure each agent's endpoint to route 100% of traffic to the newly created version. - String agent1Name = "weather-agent-1"; - String agent2Name = "weather-agent-2"; - AgentVersionDetails agent1 = agentsClient.createAgentVersion(agent1Name, agentDefinition); - try { - configureAgentEndpoint(agentsClient, agent1Name, agent1.getVersion()); - - AgentVersionDetails agent2 = agentsClient.createAgentVersion(agent2Name, agentDefinition); - try { - configureAgentEndpoint(agentsClient, agent2Name, agent2.getVersion()); - - OpenAIClient agent1Client = builder.buildAgentScopedOpenAIClient(agent1Name); - OpenAIClient agent2Client = builder.buildAgentScopedOpenAIClient(agent2Name); - - // Get response from agent1 - Response response = agent1Client.responses().create(ResponseCreateParams.builder() - .conversation(conversation.id()) - .build()); - System.out.println("Agent response from: " + agent1Name); - System.out.println("\tResponse: " + response.output().get(0).asMessage().content().get(0).asOutputText().text()); - - // Add clarification to the conversation - addMessageToConversation(conversationsClient, conversation.id(), - "You can make assumptions based on historical data. Today is October 7th.", EasyInputMessage.Role.USER); - printConversationItems(conversationsClient, conversation.id(), 3); - - // Get follow-up response from agent1 - Response followUpResponse = agent1Client.responses().create(ResponseCreateParams.builder() - .conversation(conversation.id()) - .build()); - System.out.println("Agent response from: " + agent1Name); - System.out.println("\tResponse: " + followUpResponse.output().get(0).asMessage().content().get(0).asOutputText().text()); - - // Provide all the past context and more to agent2 - addMessageToConversation(conversationsClient, conversation.id(), - "Provide suggestions opposite of what historical data indicates.", EasyInputMessage.Role.SYSTEM); - printConversationItems(conversationsClient, conversation.id(), 4); - - Response newMessageThread = agent2Client.responses().create(ResponseCreateParams.builder() - .conversation(conversation.id()) - .build()); - System.out.println("Agent response from: " + agent2Name); - System.out.println("\tResponse: " + newMessageThread.output().get(0).asMessage().content().get(0).asOutputText().text()); - } finally { - agentsClient.deleteAgentVersion(agent2Name, agent2.getVersion()); - } - } finally { - agentsClient.deleteAgentVersion(agent1Name, agent1.getVersion()); - } + // creating a new agent and their references for future responses + AgentVersionDetails agent1 = createPromptAgent(agentsClient, model, "weather-agent-1"); + AgentVersionDetails agent2 = createPromptAgent(agentsClient, model, "weather-agent-2"); + + AgentEndpointConfig agent1EndpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent1.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent1.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(agent1EndpointConfig)); + + AgentEndpointConfig agent2EndpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent2.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent2.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(agent2EndpointConfig)); + OpenAIClient agent1Client = builder.buildAgentScopedOpenAIClient(agent1.getName()); + OpenAIClient agent2Client = builder.buildAgentScopedOpenAIClient(agent2.getName()); + + // Get response from agent1 + Response response = agent1Client.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); + System.out.println("Agent response from: " + agent1.getName()); + System.out.println("\tResponse: " + response.output().get(0).asMessage().content().get(0).asOutputText().text()); + + // Add clarification to the conversation + addMessageToConversation(conversationsClient, conversation.id(), + "You can make assumptions based on historical data. Today is October 7th.", EasyInputMessage.Role.USER); + printConversationItems(conversationsClient, conversation.id(), 3); + + // Get follow-up response from agent1 + Response followUpResponse = agent1Client.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); + System.out.println("Agent response from: " + agent1.getName()); + System.out.println("\tResponse: " + followUpResponse.output().get(0).asMessage().content().get(0).asOutputText().text()); + + // Provide all the past context and more to agent2 + addMessageToConversation(conversationsClient, conversation.id(), + "Provide suggestions opposite of what historical data indicates.", EasyInputMessage.Role.SYSTEM); + printConversationItems(conversationsClient, conversation.id(), 4); + + Response newMessageThread = agent2Client.responses().create(ResponseCreateParams.builder() + .conversation(conversation.id()) + .build()); + System.out.println("Agent response from: " + agent2.getName()); + System.out.println("\tResponse: " + newMessageThread.output().get(0).asMessage().content().get(0).asOutputText().text()); } - // Points the agent endpoint at the specified version and enables the OpenAI Responses protocol on it. - private static void configureAgentEndpoint(AgentsClient agentsClient, String agentName, String agentVersion) { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agentVersion)))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + private static AgentVersionDetails createPromptAgent(AgentsClient agentsClient, String model, String name) { + PromptAgentDefinition request = new PromptAgentDefinition(model); + return agentsClient.createAgentVersion(name, request); } private static Conversation startConversation(ConversationService conversationsClient) { diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java index f32f412630040..f6e7f1dadcd02 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java @@ -3,14 +3,49 @@ package com.azure.ai.agents; +import com.azure.ai.agents.models.AgentDetails; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; +import reactor.core.publisher.Mono; + import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Collections; public class SampleUtils { + /** + * Pins an agent endpoint to a specific agent version and enables the OpenAI Responses protocol. + * + * @param agentsClient the agents client + * @param agentName the agent name + * @param agent the agent version to pin + */ + public static void pinAgentVersion(AgentsClient agentsClient, String agentName, AgentVersionDetails agent) { + agentsClient.updateAgentDetails(agentName, createPinnedEndpointOptions(agent)); + } + + /** + * Pins an agent endpoint to a specific agent version and enables the OpenAI Responses protocol. + * + * @param agentsAsyncClient the asynchronous agents client + * @param agentName the agent name + * @param agent the agent version to pin + * @return a publisher containing the updated agent details + */ + public static Mono pinAgentVersion(AgentsAsyncClient agentsAsyncClient, String agentName, + AgentVersionDetails agent) { + return agentsAsyncClient.updateAgentDetails(agentName, createPinnedEndpointOptions(agent)); + } + /** * Gets the path to a file in the sample resource folder. * @param fileName the name of the file in the sample resource folder @@ -37,4 +72,13 @@ public static Path getResourcePath(String fileName) { } throw new RuntimeException("Sample resource file not found: " + fileName); } + + private static UpdateAgentDetailsOptions createPinnedEndpointOptions(AgentVersionDetails agent) { + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + + return new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig); + } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java index 08f1c7ebeabc4..122ce1ca83406 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java @@ -15,7 +15,6 @@ import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.ProtocolConfiguration; import com.azure.ai.agents.models.ResponsesProtocolConfiguration; diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java index d595e7244bc9f..113339713a313 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java @@ -5,8 +5,15 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClient; @@ -15,13 +22,6 @@ import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseStreamEvent; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -47,26 +47,28 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // Create a CodeInterpreterTool - an Azure-specific tool for executing Python code - CodeInterpreterTool tool = new CodeInterpreterTool(); + AgentVersionDetails agent = null; - // Create agent with Code Interpreter tool - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " - + "When asked to perform calculations, use the code interpreter to run Python code.") - .setTools(Collections.singletonList(tool)); - - String agentName = "code-interpreter-streaming-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + // Create a CodeInterpreterTool - an Azure-specific tool for executing Python code + CodeInterpreterTool tool = new CodeInterpreterTool(); + + // Create agent with Code Interpreter tool + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " + + "When asked to perform calculations, use the code interpreter to run Python code.") + .setTools(Collections.singletonList(tool)); + + agent = agentsClient.createAgentVersion("code-interpreter-streaming-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.code_interpreter_sync // Stream response with Code Interpreter - observe code execution events as they arrive @@ -99,7 +101,10 @@ public static void main(String[] args) { System.out.println("\nResponse ID: " + response.id()); // END: com.azure.ai.agents.streaming.code_interpreter_sync } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java index cc38eb94197fb..94239884d144a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java @@ -5,8 +5,15 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -17,13 +24,6 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseStreamEvent; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -53,45 +53,47 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // Define a function tool with parameter schema - Map locationProp = new LinkedHashMap<>(); - locationProp.put("type", "string"); - locationProp.put("description", "The city and state, e.g. Seattle, WA"); - - Map unitProp = new LinkedHashMap<>(); - unitProp.put("type", "string"); - unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); - - Map properties = new LinkedHashMap<>(); - properties.put("location", locationProp); - properties.put("unit", unitProp); - - Map parameters = new HashMap<>(); - parameters.put("type", BinaryData.fromObject("object")); - parameters.put("properties", BinaryData.fromObject(properties)); - parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); - parameters.put("additionalProperties", BinaryData.fromObject(false)); + AgentVersionDetails agent = null; - FunctionTool tool = new FunctionTool("get_weather", parameters, true) - .setDescription("Get the current weather in a given location"); - - // Create agent with function tool - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can get weather information. " - + "When asked about the weather, use the get_weather function.") - .setTools(Collections.singletonList(tool)); - - String agentName = "function-streaming-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + // Define a function tool with parameter schema + Map locationProp = new LinkedHashMap<>(); + locationProp.put("type", "string"); + locationProp.put("description", "The city and state, e.g. Seattle, WA"); + + Map unitProp = new LinkedHashMap<>(); + unitProp.put("type", "string"); + unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); + + Map properties = new LinkedHashMap<>(); + properties.put("location", locationProp); + properties.put("unit", unitProp); + + Map parameters = new HashMap<>(); + parameters.put("type", BinaryData.fromObject("object")); + parameters.put("properties", BinaryData.fromObject(properties)); + parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); + parameters.put("additionalProperties", BinaryData.fromObject(false)); + + FunctionTool tool = new FunctionTool("get_weather", parameters, true) + .setDescription("Get the current weather in a given location"); + + // Create agent with function tool + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can get weather information. " + + "When asked about the weather, use the get_weather function.") + .setTools(Collections.singletonList(tool)); + + agent = agentsClient.createAgentVersion("function-streaming-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.function_call_sync // Stream response with function tool - observe function call arguments and text as they arrive @@ -127,7 +129,10 @@ public static void main(String[] args) { } // END: com.azure.ai.agents.streaming.function_call_sync } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java index 11596336ef8b0..ef2f87b38c499 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java @@ -5,7 +5,14 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClient; @@ -16,13 +23,6 @@ import com.openai.models.responses.ResponseStreamEvent; import java.util.Collections; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates how to create a streaming response using the synchronous client. @@ -45,21 +45,23 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // Create an agent - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that tells short, engaging stories."); + AgentVersionDetails agent = null; - String agentName = "streaming-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + // Create an agent + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that tells short, engaging stories."); + agent = agentsClient.createAgentVersion("streaming-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + agentsClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.simple_sync // Use ResponseAccumulator to collect streamed events into a final Response @@ -84,7 +86,10 @@ public static void main(String[] args) { System.out.println("\nResponse ID: " + response.id()); // END: com.azure.ai.agents.streaming.simple_sync } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java index 65774d70739f7..0a65efb73d111 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java @@ -5,23 +5,19 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.A2AProtocolVersion; import com.azure.ai.agents.models.A2ATool; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with an Agent-to-Agent (A2A) tool @@ -45,6 +41,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("a2a-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create agent-to-agent tool with A2A protocol version and connection ID A2ATool a2aTool = new A2ATool(A2AProtocolVersion.V1_0) @@ -54,27 +53,28 @@ public static void main(String[] args) { .setInstructions("You are a coordinator agent that can communicate with other agents.") .setTools(Collections.singletonList(a2aTool)); - String agentName = "a2a-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("a2a-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("What can the secondary agent do?") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java index f8888ed22c210..ad3a30bfb3a9a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java @@ -5,21 +5,16 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.A2AProtocolVersion; import com.azure.ai.agents.models.A2ATool; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -57,25 +52,23 @@ public static void main(String[] args) { .setInstructions("You are a coordinator agent that can communicate with other agents.") .setTools(Collections.singletonList(a2aTool)); - String agentName = "a2a-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("a2a-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("What can the secondary agent do?") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java index 6d91192625e6c..4f16e064679f2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java @@ -5,7 +5,9 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AISearchIndexResource; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AzureAISearchQueryType; import com.azure.ai.agents.models.AzureAISearchTool; import com.azure.ai.agents.models.AzureAISearchToolResource; @@ -14,18 +16,11 @@ import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; -import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; - import java.time.Duration; import java.util.Arrays; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; +import reactor.core.publisher.Mono; /** * This sample demonstrates (using the async client) how to create an agent with the Azure AI Search tool @@ -51,6 +46,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("ai-search-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create Azure AI Search tool with index configuration AzureAISearchTool aiSearchTool = new AzureAISearchTool( @@ -67,27 +65,28 @@ public static void main(String[] args) { + "Always provide citations for answers using the tool.") .setTools(Collections.singletonList(aiSearchTool)); - // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, - // so responses.create(...) below does not need to send an agent_reference in its body. - String agentName = "ai-search-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("ai-search-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Search for information about Azure AI services") - .build())) - .doOnNext(response -> System.out.println("Response: " + response.output())); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java index 7688aef2d2c42..9c318dc39ff02 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AISearchIndexResource; import com.azure.ai.agents.models.AzureAISearchQueryType; import com.azure.ai.agents.models.AzureAISearchTool; @@ -15,13 +17,6 @@ import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -69,25 +64,23 @@ public static void main(String[] args) { + "Always provide citations for answers using the tool.") .setTools(Collections.singletonList(aiSearchTool)); - String agentName = "ai-search-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + AgentVersionDetails agent = agentsClient.createAgentVersion("ai-search-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .input("Search for information about Azure AI services") - .build()); + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .input("Search for information about Azure AI services") + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java index eb5072e0ed550..7c10fc2c4e795 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AzureFunctionBinding; import com.azure.ai.agents.models.AzureFunctionDefinition; import com.azure.ai.agents.models.AzureFunctionDefinitionDetails; @@ -18,19 +20,13 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ToolChoiceOptions; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an Azure Function tool @@ -58,6 +54,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("azure-function-agent"); + + AtomicReference agentRef = new AtomicReference<>(); Map locationProp = new LinkedHashMap(); locationProp.put("type", "string"); @@ -85,26 +84,29 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(azureFunctionTool)); - String agentName = "azure-function-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("azure-function-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) .input("What is the weather in Seattle?") - .build())) - .doOnNext(response -> System.out.println("Response: " + response.output())); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java index 441187c78fc67..7391265dc9ae6 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.AzureFunctionBinding; import com.azure.ai.agents.models.AzureFunctionDefinition; import com.azure.ai.agents.models.AzureFunctionDefinitionDetails; @@ -18,13 +20,6 @@ import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ToolChoiceOptions; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.HashMap; @@ -90,26 +85,23 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(azureFunctionTool)); - String agentName = "azure-function-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + AgentVersionDetails agent = agentsClient.createAgentVersion("azure-function-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + try { + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .toolChoice(ToolChoiceOptions.REQUIRED) - .input("What is the weather in Seattle?") - .build()); + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .toolChoice(ToolChoiceOptions.REQUIRED) + .input("What is the weather in Seattle?") + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java index 70f24d650c5a1..3514090b702ba 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java @@ -5,26 +5,22 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingCustomSearchConfiguration; import com.azure.ai.agents.models.BingCustomSearchPreviewTool; import com.azure.ai.agents.models.BingCustomSearchToolParameters; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Arrays; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with the Bing Custom Search tool @@ -50,6 +46,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("bing-custom-search-agent"); + + AtomicReference agentRef = new AtomicReference<>(); BingCustomSearchPreviewTool bingCustomSearchTool = new BingCustomSearchPreviewTool( new BingCustomSearchToolParameters(Arrays.asList( @@ -62,27 +61,28 @@ public static void main(String[] args) { + "Use the available Bing Custom Search tools to answer questions and perform tasks.") .setTools(Collections.singletonList(bingCustomSearchTool)); - String agentName = "bing-custom-search-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("bing-custom-search-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Search for the latest Azure AI documentation") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java index 3012a7c5b5ade..ae49955179217 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingCustomSearchConfiguration; import com.azure.ai.agents.models.BingCustomSearchPreviewTool; import com.azure.ai.agents.models.BingCustomSearchToolParameters; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -70,25 +65,22 @@ public static void main(String[] args) { + "Use the available Bing Custom Search tools to answer questions and perform tasks.") .setTools(Collections.singletonList(bingCustomSearchTool)); - String agentName = "bing-custom-search-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("bing-custom-search-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Search for the latest Azure AI documentation") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java index 5a3aadfe86a1f..584b4680cdb65 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java @@ -5,25 +5,21 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingGroundingSearchConfiguration; import com.azure.ai.agents.models.BingGroundingSearchToolParameters; import com.azure.ai.agents.models.BingGroundingTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Arrays; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Bing Grounding tool @@ -47,6 +43,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("bing-grounding-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create Bing grounding tool with connection configuration BingGroundingTool bingTool = new BingGroundingTool( @@ -59,27 +58,28 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant. Use Bing to find up-to-date information.") .setTools(Collections.singletonList(bingTool)); - String agentName = "bing-grounding-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("bing-grounding-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("What are the latest developments in AI?") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java index 86b09062a7d31..3a7dcf3428210 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BingGroundingSearchConfiguration; import com.azure.ai.agents.models.BingGroundingSearchToolParameters; import com.azure.ai.agents.models.BingGroundingTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Arrays; @@ -62,25 +57,23 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant. Use Bing to find up-to-date information.") .setTools(Collections.singletonList(bingTool)); - String agentName = "bing-grounding-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("bing-grounding-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("What are the latest developments in AI?") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java index 129f9026c4abd..aa612e04121ca 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java @@ -5,24 +5,20 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BrowserAutomationPreviewTool; import com.azure.ai.agents.models.BrowserAutomationToolConnectionParameters; import com.azure.ai.agents.models.BrowserAutomationToolParameters; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Browser Automation tool @@ -46,6 +42,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("browser-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create browser automation tool with connection configuration BrowserAutomationPreviewTool browserTool = new BrowserAutomationPreviewTool( @@ -58,27 +57,28 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can interact with web pages.") .setTools(Collections.singletonList(browserTool)); - String agentName = "browser-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("browser-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Navigate to microsoft.com and summarize the main content") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java index 2e4da2377f9fd..4cb64445f1d5e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.BrowserAutomationPreviewTool; import com.azure.ai.agents.models.BrowserAutomationToolConnectionParameters; import com.azure.ai.agents.models.BrowserAutomationToolParameters; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -61,25 +56,23 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can interact with web pages.") .setTools(Collections.singletonList(browserTool)); - String agentName = "browser-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("browser-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Navigate to microsoft.com and summarize the main content") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java index 3f0276f8a805d..96c9ca4cb9cb7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -15,16 +17,10 @@ import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create an agent with the Code Interpreter tool @@ -46,6 +42,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("code-interpreter-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create a CodeInterpreterTool with default auto container configuration CodeInterpreterTool tool = new CodeInterpreterTool(); @@ -55,48 +54,47 @@ public static void main(String[] args) { + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") .setTools(Collections.singletonList(tool)); - // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, - // so responses.create(...) below does not need to send an agent_reference in its body. - String agentName = "code-interpreter-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("code-interpreter-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Calculate the first 10 prime numbers and show me the Python code you used.") - .build())) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); - }); - } + .build()))); + }) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); + }); + } - if (outputItem.codeInterpreterCall().isPresent()) { - ResponseCodeInterpreterToolCall codeCall = outputItem.codeInterpreterCall().get(); - System.out.println("\n--- Code Interpreter Execution ---"); - System.out.println("Call ID: " + codeCall.id()); - codeCall.code().ifPresent(code -> { - System.out.println("Python Code Executed:\n" + code); - }); - System.out.println("Status: " + codeCall.status()); - } - } + if (outputItem.codeInterpreterCall().isPresent()) { + ResponseCodeInterpreterToolCall codeCall = outputItem.codeInterpreterCall().get(); + System.out.println("\n--- Code Interpreter Execution ---"); + System.out.println("Call ID: " + codeCall.id()); + codeCall.code().ifPresent(code -> { + System.out.println("Python Code Executed:\n" + code); }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + System.out.println("Status: " + codeCall.status()); + } + } + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java index 0d2d2a5254836..78fbfcaca227f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -15,13 +17,6 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -46,32 +41,31 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // BEGIN: com.azure.ai.agents.define_code_interpreter - // Create a CodeInterpreterTool with default auto container configuration - CodeInterpreterTool tool = new CodeInterpreterTool(); - // END: com.azure.ai.agents.define_code_interpreter - - // Create the agent definition with Code Interpreter tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " - + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") - .setTools(Collections.singletonList(tool)); + AgentVersionDetails agent = null; - String agentName = "code-interpreter-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + // BEGIN: com.azure.ai.agents.define_code_interpreter + // Create a CodeInterpreterTool with default auto container configuration + CodeInterpreterTool tool = new CodeInterpreterTool(); + // END: com.azure.ai.agents.define_code_interpreter + // Create the agent definition with Code Interpreter tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can execute Python code to solve problems. " + + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") + .setTools(Collections.singletonList(tool)); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + agent = agentsClient.createAgentVersion("code-interpreter-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers and show me the Python code you used.") - .build()); + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .input("Calculate the first 10 prime numbers and show me the Python code you used.") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -95,7 +89,10 @@ public static void main(String[] args) { } } } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java index b15401db0e424..229aa4b7d2f3a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java @@ -5,7 +5,9 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.AgentsServiceVersion; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ComputerEnvironment; import com.azure.ai.agents.models.ComputerUsePreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -26,19 +28,13 @@ import com.openai.models.responses.ResponseInputText; import com.openai.models.responses.ResponseOutputItem; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** @@ -75,6 +71,7 @@ public static void main(String[] args) { .serviceVersion(AgentsServiceVersion.getLatest()); AgentsAsyncClient agentsClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("ComputerUseAgent"); // Load screenshot assets Map screenshots; @@ -98,6 +95,9 @@ public static void main(String[] args) { + "Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.") .setTools(Collections.singletonList(tool)); + // Use AtomicReference to track the agent for cleanup + AtomicReference agentRef = new AtomicReference<>(); + // Build the initial input using proper OpenAI SDK types List contentParts = Arrays.asList( // Text part @@ -122,39 +122,39 @@ public static void main(String[] args) { .build()) ); - final Map screenshotsForLoop = screenshots; - - // Create the agent version, pin the agent endpoint to it, then run the interaction loop - // through an agent-scoped OpenAI client. The endpoint URL identifies the agent, so - // responses.create(...) below does not need to send an agent_reference in its body. - String agentName = "ComputerUseAgent"; - Mono.usingWhen( - agentsClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - - System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); - - // Send initial request - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + // Create agent and run the interaction loop + agentsClient.createAgentVersion("ComputerUseAgent", agentDefinition) + .doOnNext(agent -> { + agentRef.set(agent); + System.out.printf("Agent created (id: %s, name: %s, version: %s)%n", + agent.getId(), agent.getName(), agent.getVersion()); + }) + .flatMap(agent -> { + + System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); + + // Send initial request + return SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .inputOfResponse(initialInput) .truncation(ResponseCreateParams.Truncation.AUTO) - .build())) - .doOnNext(response -> System.out.printf("Initial response received (ID: %s)%n", response.id())) - .flatMap(response -> runInteractionLoop( - openAIAsyncClient, response, screenshotsForLoop, SearchState.INITIAL, 0)); - }, - agent -> agentsClient.deleteAgentVersion(agentName, agent.getVersion())) - .doOnError(e -> System.err.println("Error: " + e.getMessage())) - .block(); + .build()))) + .doOnNext(response -> System.out.printf("Initial response received (ID: %s)%n", response.id())) + .flatMap(response -> runInteractionLoop( + openAIAsyncClient, response, screenshots, SearchState.INITIAL, 0)); + }) + .doFinally(signalType -> { + System.out.println("\nCleaning up..."); + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")) + .doOnError(e -> System.out.println("Failed to delete agent: " + e.getMessage())) + .subscribe(); + } + }) + .block(); // Block to wait for completion in main method } /** @@ -217,11 +217,12 @@ private static Mono runInteractionLoop( .build()) ); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() - .previousResponseId(response.id()) - .inputOfResponse(followUpInput) - .truncation(ResponseCreateParams.Truncation.AUTO) - .build())) + return Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .previousResponseId(response.id()) + .inputOfResponse(followUpInput) + .truncation(ResponseCreateParams.Truncation.AUTO) + .build())) .doOnNext(newResponse -> System.out.printf("Follow-up response received (ID: %s)%n", newResponse.id())) .flatMap(newResponse -> runInteractionLoop( openAIAsyncClient, newResponse, screenshots, newState, iteration + 1)); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java index b8b472bfb672f..e2ae5df6fbf6e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java @@ -5,7 +5,9 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.AgentsServiceVersion; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ComputerEnvironment; import com.azure.ai.agents.models.ComputerUsePreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -25,13 +27,6 @@ import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseInputText; import com.openai.models.responses.ResponseOutputItem; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.io.IOException; import java.util.Arrays; @@ -87,30 +82,28 @@ public static void main(String[] args) { return; } - // BEGIN: com.azure.ai.agents.define_computer_use - ComputerUsePreviewTool tool = new ComputerUsePreviewTool( - ComputerEnvironment.WINDOWS, - 1026, - 769 - ); - // END: com.azure.ai.agents.define_computer_use - - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a computer automation assistant." - + "Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.") - .setTools(Collections.singletonList(tool)); - - String agentName = "ComputerUseAgent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + AgentVersionDetails agent = null; + try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + // BEGIN: com.azure.ai.agents.define_computer_use + ComputerUsePreviewTool tool = new ComputerUsePreviewTool( + ComputerEnvironment.WINDOWS, + 1026, + 769 + ); + // END: com.azure.ai.agents.define_computer_use + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a computer automation assistant." + + "Be direct and efficient. When you reach the search results page, read and describe the actual search result titles and descriptions you can see.") + .setTools(Collections.singletonList(tool)); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + agent = agentsClient.createAgentVersion("ComputerUseAgent", agentDefinition); + System.out.printf("Agent created (id: %s, name: %s, version: %s)%n", + agent.getId(), agent.getName(), agent.getVersion()); + + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // Initial request with screenshot - start with Bing search page System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); @@ -140,10 +133,11 @@ public static void main(String[] args) { .build()) ); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .inputOfResponse(initialInput) - .truncation(ResponseCreateParams.Truncation.AUTO) - .build()); + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .inputOfResponse(initialInput) + .truncation(ResponseCreateParams.Truncation.AUTO) + .build()); System.out.printf("Initial response received (ID: %s)%n", response.id()); @@ -196,16 +190,25 @@ public static void main(String[] args) { .build()) ); - response = openAIClient.responses().create(ResponseCreateParams.builder() - .previousResponseId(response.id()) - .inputOfResponse(followUpInput) - .truncation(ResponseCreateParams.Truncation.AUTO) - .build()); + response = openAIClient.responses().create( + ResponseCreateParams.builder() + .previousResponseId(response.id()) + .inputOfResponse(followUpInput) + .truncation(ResponseCreateParams.Truncation.AUTO) + .build()); System.out.printf("Follow-up response received (ID: %s)%n", response.id()); } } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + System.out.println("\nCleaning up..."); + if (agent != null) { + try { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } catch (Exception e) { + System.out.println("Failed to delete agent: " + e.getMessage()); + } + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java index f72a04ffc8570..1df24309a895f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java @@ -5,23 +5,19 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with a Custom Code Interpreter @@ -47,6 +43,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("CustomCodeInterpreterAgent"); + + AtomicReference agentRef = new AtomicReference<>(); McpTool customCodeInterpreter = new McpTool("custom-code-interpreter") .setServerUrl(mcpServerUrl) @@ -57,27 +56,28 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.") .setTools(Collections.singletonList(customCodeInterpreter)); - String agentName = "CustomCodeInterpreterAgent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("CustomCodeInterpreterAgent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Calculate the factorial of 10 using Python.") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java index 87eb03080598d..a6a50871b2f85 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java @@ -5,20 +5,15 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -58,25 +53,25 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.") .setTools(Collections.singletonList(customCodeInterpreter)); - String agentName = "CustomCodeInterpreterAgent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion( + "CustomCodeInterpreterAgent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Calculate the factorial of 10 using Python.") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java index 7d3122e5f70a4..d740e55c1f13b 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java @@ -5,25 +5,21 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricDataAgentToolParameters; import com.azure.ai.agents.models.MicrosoftFabricPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.ToolProjectConnection; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Arrays; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Microsoft Fabric tool @@ -47,6 +43,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("fabric-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create Microsoft Fabric tool with connection configuration MicrosoftFabricPreviewTool fabricTool = new MicrosoftFabricPreviewTool( @@ -60,27 +59,28 @@ public static void main(String[] args) { .setInstructions("You are a data assistant that can query Microsoft Fabric data.") .setTools(Collections.singletonList(fabricTool)); - String agentName = "fabric-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("fabric-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Query the latest sales data from Microsoft Fabric") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java index ddf3b565389b4..33f2075fe8496 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricIqPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -15,13 +17,6 @@ import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; @@ -52,6 +47,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); FabricIqPreviewTool fabricIqTool = new FabricIqPreviewTool(fabricIqConnectionId) .setServerLabel("fabric-iq-tool") @@ -61,27 +57,30 @@ public static void main(String[] args) { .setInstructions("Use the available Fabric IQ tools to answer questions and perform tasks.") .setTools(Collections.singletonList(fabricIqTool)); - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + Mono workflow = Mono.usingWhen( + agentsAsyncClient.createAgentVersion(agentName, agentDefinition), + agent -> { + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input(userInput) - .build())) - .doOnNext(FabricIQAsync::printResponse); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) - .doOnError(error -> System.err.println("Error: " + error.getMessage())) - .timeout(Duration.ofSeconds(300)) - .block(); + .build()))) + .doOnNext(FabricIQAsync::printResponse) + .then(); + }, + agent -> cleanup(agentsAsyncClient, agent), + (agent, error) -> cleanup(agentsAsyncClient, agent), + agent -> cleanup(agentsAsyncClient, agent)) + .timeout(Duration.ofSeconds(300)); + + workflow.block(); + } + + private static Mono cleanup(AgentsAsyncClient agentsAsyncClient, AgentVersionDetails agent) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); } private static void printResponse(Response response) { diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java index 6cda112edd784..e5925603127c2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricIqPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -64,23 +59,21 @@ public static void main(String[] args) { .setTools(Collections.singletonList(fabricIqTool)); AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input(userInput) - .build()); + .build()); printResponse(response); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java index 47e353e62e500..3045977a7414d 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FabricDataAgentToolParameters; import com.azure.ai.agents.models.MicrosoftFabricPreviewTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.ToolProjectConnection; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Arrays; @@ -63,25 +58,23 @@ public static void main(String[] args) { .setInstructions("You are a data assistant that can query Microsoft Fabric data.") .setTools(Collections.singletonList(fabricTool)); - String agentName = "fabric-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("fabric-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Query the latest sales data from Microsoft Fabric") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java index 5f0610eb1e8ee..ffe0106d9ec19 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java @@ -5,24 +5,19 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseFunctionToolCall; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Arrays; @@ -30,6 +25,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create an agent with a Function Calling tool @@ -51,6 +47,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("function-call-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create a FunctionTool with parameters schema // Use BinaryData.fromObject() to produce correct JSON types (not double-encoded strings) @@ -81,45 +80,46 @@ public static void main(String[] args) { + "When asked about the weather, use the get_weather function to retrieve weather data.") .setTools(Collections.singletonList(tool)); - String agentName = "function-call-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() - .input("What's the weather like in Seattle?") - .build())) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); - }); - } + agentsAsyncClient.createAgentVersion("function-call-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - if (outputItem.functionCall().isPresent()) { - ResponseFunctionToolCall functionCall = outputItem.functionCall().get(); - System.out.println("\n--- Function Tool Call ---"); - System.out.println("Call ID: " + functionCall.callId()); - System.out.println("Function Name: " + functionCall.name()); - System.out.println("Arguments: " + functionCall.arguments()); - System.out.println("Status: " + functionCall.status()); - } - } + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .input("What's the weather like in Seattle?") + .build()))); + }) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + } + + if (outputItem.functionCall().isPresent()) { + ResponseFunctionToolCall functionCall = outputItem.functionCall().get(); + System.out.println("\n--- Function Tool Call ---"); + System.out.println("Call ID: " + functionCall.callId()); + System.out.println("Function Name: " + functionCall.name()); + System.out.println("Arguments: " + functionCall.arguments()); + System.out.println("Status: " + functionCall.status()); + } + } + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(30)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java index bf14007c48ca7..32d9ee0592af4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; @@ -16,13 +18,6 @@ import com.openai.models.responses.ResponseFunctionToolCall; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; @@ -51,50 +46,49 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // Create a FunctionTool with parameters schema - // Use BinaryData.fromObject() to produce correct JSON types (not double-encoded strings) - Map locationProp = new LinkedHashMap(); - locationProp.put("type", "string"); - locationProp.put("description", "The city and state, e.g. Seattle, WA"); - - Map unitProp = new LinkedHashMap(); - unitProp.put("type", "string"); - unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); - - Map properties = new LinkedHashMap(); - properties.put("location", locationProp); - properties.put("unit", unitProp); - - Map parameters = new HashMap(); - parameters.put("type", BinaryData.fromObject("object")); - parameters.put("properties", BinaryData.fromObject(properties)); - parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); - parameters.put("additionalProperties", BinaryData.fromObject(false)); - - FunctionTool tool = new FunctionTool("get_weather", parameters, true) - .setDescription("Get the current weather in a given location"); - - // Create the agent definition with Function tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can get weather information. " - + "When asked about the weather, use the get_weather function to retrieve weather data.") - .setTools(Collections.singletonList(tool)); - - String agentName = "function-call-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + AgentVersionDetails agent = null; + try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + // Create a FunctionTool with parameters schema + // Use BinaryData.fromObject() to produce correct JSON types (not double-encoded strings) + Map locationProp = new LinkedHashMap(); + locationProp.put("type", "string"); + locationProp.put("description", "The city and state, e.g. Seattle, WA"); + + Map unitProp = new LinkedHashMap(); + unitProp.put("type", "string"); + unitProp.put("enum", Arrays.asList("celsius", "fahrenheit")); + + Map properties = new LinkedHashMap(); + properties.put("location", locationProp); + properties.put("unit", unitProp); + Map parameters = new HashMap(); + parameters.put("type", BinaryData.fromObject("object")); + parameters.put("properties", BinaryData.fromObject(properties)); + parameters.put("required", BinaryData.fromObject(Arrays.asList("location", "unit"))); + parameters.put("additionalProperties", BinaryData.fromObject(false)); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + FunctionTool tool = new FunctionTool("get_weather", parameters, true) + .setDescription("Get the current weather in a given location"); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .input("What's the weather like in Seattle?") - .build()); + // Create the agent definition with Function tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can get weather information. " + + "When asked about the weather, use the get_weather function to retrieve weather data.") + .setTools(Collections.singletonList(tool)); + + agent = agentsClient.createAgentVersion("function-call-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .input("What's the weather like in Seattle?") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -117,7 +111,10 @@ public static void main(String[] args) { } } } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java index 277dead2efdb2..c03fe9dde1778 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ImageGenTool; import com.azure.ai.agents.models.ImageGenToolModel; import com.azure.ai.agents.models.ImageGenToolQuality; @@ -12,18 +14,12 @@ import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the Image Generation tool @@ -47,6 +43,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("image-gen-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create image generation tool with model, quality, and size ImageGenTool imageGenTool = new ImageGenTool() @@ -58,27 +57,28 @@ public static void main(String[] args) { .setInstructions("You are a creative assistant that can generate images based on descriptions.") .setTools(Collections.singletonList(imageGenTool)); - String agentName = "image-gen-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("image-gen-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Generate an image of a sunset over a mountain range") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java index a3d2f17799fbb..68e8604552815 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ImageGenTool; import com.azure.ai.agents.models.ImageGenToolModel; import com.azure.ai.agents.models.ImageGenToolQuality; @@ -12,16 +14,9 @@ import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -61,21 +56,18 @@ public static void main(String[] args) { .setInstructions("You are a creative assistant that can generate images based on descriptions.") .setTools(Collections.singletonList(imageGenTool)); - String agentName = "image-gen-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("image-gen-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Generate an image of a sunset over a mountain range") - .build()); + .build()); // The response output may include image_generation_call items with base64-encoded image data. // This sample prints the response status and the number of output items; image extraction @@ -83,7 +75,8 @@ public static void main(String[] args) { System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Output items: " + response.output().size()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java index 379ad379b4df7..f457ef48839d1 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -15,18 +17,12 @@ import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with a Model Context Protocol (MCP) tool @@ -51,6 +47,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("mcp-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create an MCP tool that connects to a remote MCP server // Uses gitmcp.io to expose a GitHub repository as an MCP-compatible server @@ -63,77 +62,77 @@ public static void main(String[] args) { + "Use the available MCP tools to answer questions and perform tasks.") .setTools(Collections.singletonList(tool)); - String agentName = "mcp-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); + agentsAsyncClient.createAgentVersion("mcp-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Please summarize the Azure REST API specifications Readme") - .build())) - .flatMap(response -> { - // Process MCP approval requests - List approvals = new ArrayList(); - for (ResponseOutputItem item : response.output()) { - if (item.isMcpApprovalRequest()) { - ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); - System.out.printf("MCP approval requested: server=%s, id=%s%n", - request.serverLabel(), request.id()); + .build()))); + }) + .flatMap(response -> { + // Process MCP approval requests + List approvals = new ArrayList(); + for (ResponseOutputItem item : response.output()) { + if (item.isMcpApprovalRequest()) { + ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); + System.out.printf("MCP approval requested: server=%s, id=%s%n", + request.serverLabel(), request.id()); - approvals.add(ResponseInputItem.ofMcpApprovalResponse( - ResponseInputItem.McpApprovalResponse.builder() - .approvalRequestId(request.id()) - .approve(true) - .build())); - } - } + approvals.add(ResponseInputItem.ofMcpApprovalResponse( + ResponseInputItem.McpApprovalResponse.builder() + .approvalRequestId(request.id()) + .approve(true) + .build())); + } + } - if (!approvals.isEmpty()) { - System.out.println("Sending " + approvals.size() + " approval(s)..."); - return Mono.fromFuture(openAIAsyncClient.responses().create( - ResponseCreateParams.builder() - .inputOfResponse(approvals) - .previousResponseId(response.id()) - .build())); - } + if (!approvals.isEmpty()) { + System.out.println("Sending " + approvals.size() + " approval(s)..."); + return Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build())); + } - return Mono.just(response); - }) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); - }); - } - - if (outputItem.mcpCall().isPresent()) { - ResponseOutputItem.McpCall mcpCall = outputItem.mcpCall().get(); - System.out.println("\n--- MCP Tool Call ---"); - System.out.println("Call ID: " + mcpCall.id()); - System.out.println("Server Label: " + mcpCall.serverLabel()); - System.out.println("Tool Name: " + mcpCall.name()); - System.out.println("Arguments: " + mcpCall.arguments()); - mcpCall.status().ifPresent(status -> System.out.println("Status: " + status)); - mcpCall.output().ifPresent(output -> System.out.println("Output: " + output)); - mcpCall.error().ifPresent(error -> System.out.println("Error: " + error)); - } - } + return Mono.just(response); + }) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + } + + if (outputItem.mcpCall().isPresent()) { + ResponseOutputItem.McpCall mcpCall = outputItem.mcpCall().get(); + System.out.println("\n--- MCP Tool Call ---"); + System.out.println("Call ID: " + mcpCall.id()); + System.out.println("Server Label: " + mcpCall.serverLabel()); + System.out.println("Tool Name: " + mcpCall.name()); + System.out.println("Arguments: " + mcpCall.arguments()); + mcpCall.status().ifPresent(status -> System.out.println("Status: " + status)); + mcpCall.output().ifPresent(output -> System.out.println("Output: " + output)); + mcpCall.error().ifPresent(error -> System.out.println("Error: " + error)); + } + } + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java index 643a712675520..d302a2918f3cc 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -15,13 +17,6 @@ import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.ArrayList; import java.util.Collections; @@ -51,35 +46,34 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // Create an MCP tool that connects to a remote MCP server - // BEGIN: com.azure.ai.agents.built_in_mcp - // Uses gitmcp.io to expose a GitHub repository as an MCP-compatible server - McpTool tool = new McpTool("api-specs") - .setServerUrl("https://gitmcp.io/Azure/azure-rest-api-specs") - .setRequireApproval("always"); - // END: com.azure.ai.agents.built_in_mcp - - // Create the agent definition with MCP tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful agent that can use MCP tools to assist users. " - + "Use the available MCP tools to answer questions and perform tasks.") - .setTools(Collections.singletonList(tool)); - - String agentName = "mcp-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + AgentVersionDetails agent = null; - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .input("Please summarize the Azure REST API specifications Readme") - .build()); + try { + // Create an MCP tool that connects to a remote MCP server + // BEGIN: com.azure.ai.agents.built_in_mcp + // Uses gitmcp.io to expose a GitHub repository as an MCP-compatible server + McpTool tool = new McpTool("api-specs") + .setServerUrl("https://gitmcp.io/Azure/azure-rest-api-specs") + .setRequireApproval("always"); + // END: com.azure.ai.agents.built_in_mcp + + // Create the agent definition with MCP tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful agent that can use MCP tools to assist users. " + + "Use the available MCP tools to answer questions and perform tasks.") + .setTools(Collections.singletonList(tool)); + + agent = agentsClient.createAgentVersion("mcp-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .input("Please summarize the Azure REST API specifications Readme") + .build()); // Process MCP approval requests — the server requires approval before executing tools List approvals = new ArrayList(); @@ -100,10 +94,11 @@ public static void main(String[] args) { // If approvals were needed, send them back and get the final response if (!approvals.isEmpty()) { System.out.println("Sending " + approvals.size() + " approval(s)..."); - response = openAIClient.responses().create(ResponseCreateParams.builder() - .inputOfResponse(approvals) - .previousResponseId(response.id()) - .build()); + response = openAIClient.responses().create( + ResponseCreateParams.builder() + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build()); } // Process and display the final response @@ -130,7 +125,10 @@ public static void main(String[] args) { } } } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java index 351542ba643e6..b46607f57f8b2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -14,18 +16,12 @@ import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an MCP tool @@ -49,6 +45,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("mcp-connection-agent"); + + AtomicReference agentRef = new AtomicReference<>(); McpTool mcpTool = new McpTool("api-specs") .setServerUrl("https://api.githubcopilot.com/mcp") @@ -59,54 +58,56 @@ public static void main(String[] args) { .setInstructions("Use MCP tools as needed") .setTools(Collections.singletonList(mcpTool)); - String agentName = "mcp-connection-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); + agentsAsyncClient.createAgentVersion("mcp-connection-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("What is my username in GitHub profile?") - .build())) - .flatMap(response -> { - // Process MCP approval requests - List approvals = new ArrayList<>(); - for (ResponseOutputItem item : response.output()) { - if (item.isMcpApprovalRequest()) { - ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); - System.out.printf("MCP approval requested: server=%s, id=%s%n", - request.serverLabel(), request.id()); + .build()))); + }) + .flatMap(response -> { + // Process MCP approval requests + List approvals = new ArrayList<>(); + for (ResponseOutputItem item : response.output()) { + if (item.isMcpApprovalRequest()) { + ResponseOutputItem.McpApprovalRequest request = item.asMcpApprovalRequest(); + System.out.printf("MCP approval requested: server=%s, id=%s%n", + request.serverLabel(), request.id()); - approvals.add(ResponseInputItem.ofMcpApprovalResponse( - ResponseInputItem.McpApprovalResponse.builder() - .approvalRequestId(request.id()) - .approve(true) - .build())); - } - } + approvals.add(ResponseInputItem.ofMcpApprovalResponse( + ResponseInputItem.McpApprovalResponse.builder() + .approvalRequestId(request.id()) + .approve(true) + .build())); + } + } - if (!approvals.isEmpty()) { - System.out.println("Sending " + approvals.size() + " approval(s)..."); - return Mono.fromFuture(openAIAsyncClient.responses().create( - ResponseCreateParams.builder() - .inputOfResponse(approvals) - .previousResponseId(response.id()) - .build())); - } + if (!approvals.isEmpty()) { + System.out.println("Sending " + approvals.size() + " approval(s)..."); + return Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build())); + } - return Mono.just(response); - }) - .doOnNext(response -> System.out.println("Response: " + response.output())); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + return Mono.just(response); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java index 1544d1a1d6874..d1f6b23100605 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.McpTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; @@ -16,13 +18,6 @@ import com.openai.models.responses.ResponseInputItem; import com.openai.models.responses.ResponseOutputItem; import com.openai.services.blocking.ConversationService; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.ArrayList; import java.util.Collections; @@ -69,26 +64,22 @@ public static void main(String[] args) { .setInstructions("Use MCP tools as needed") .setTools(Collections.singletonList(mcpTool)); - String agentName = "mcp-connection-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + AgentVersionDetails agent = agentsClient.createAgentVersion("mcp-connection-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // Create a conversation for context Conversation conversation = conversationService.create(); // Send initial request that triggers the MCP tool - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .conversation(conversation.id()) - .input("What is my username in GitHub profile?") - .build()); + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .conversation(conversation.id()) + .input("What is my username in GitHub profile?") + .build()); // Process MCP approval requests: approve each one so the agent can proceed List approvals = new ArrayList<>(); @@ -110,18 +101,20 @@ public static void main(String[] args) { System.out.println("Sending " + approvals.size() + " approval(s)..."); // Send approvals back to continue the agent's work - Response followUp = openAIClient.responses().create(ResponseCreateParams.builder() - .conversation(conversation.id()) - .inputOfResponse(approvals) - .previousResponseId(response.id()) - .build()); + Response followUp = openAIClient.responses().create( + ResponseCreateParams.builder() + .conversation(conversation.id()) + .inputOfResponse(approvals) + .previousResponseId(response.id()) + .build()); System.out.println("Response: " + followUp.output()); } else { System.out.println("Response: " + response.output()); } } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java index c3fb4798fe8ab..6003da2c1b46e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java @@ -5,18 +5,14 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.BetaMemoryStoresClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.MemorySearchPreviewTool; import com.azure.ai.agents.models.MemoryStoreDefaultDefinition; import com.azure.ai.agents.models.MemoryStoreDefaultOptions; import com.azure.ai.agents.models.MemoryStoreDetails; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -56,6 +52,7 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("memory-search-agent"); ConversationServiceAsync conversationServiceAsync = builder.buildOpenAIAsyncClient().conversations(); // Memory store operations use sync client for setup/teardown BetaMemoryStoresClient memoryStoresClient = builder.beta().buildBetaMemoryStoresClient(); @@ -63,6 +60,7 @@ public static void main(String[] args) throws Exception { String memoryStoreName = "my_memory_store"; String scope = "user_123"; + AtomicReference agentRef = new AtomicReference<>(); AtomicReference firstConvRef = new AtomicReference<>(); AtomicReference secondConvRef = new AtomicReference<>(); @@ -86,44 +84,38 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - String agentName = "memory-search-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); + agentsAsyncClient.createAgentVersion("memory-search-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - // First conversation: teach a preference - return Mono.fromFuture(conversationServiceAsync.create()) - .flatMap(conv -> { - firstConvRef.set(conv.id()); - return Mono.fromFuture(openAIAsyncClient.responses().create( - ResponseCreateParams.builder() - .conversation(conv.id()) - .input("I prefer dark roast coffee") - .build())); - }) - .doOnNext(response -> System.out.println("First response received")) - .delayElement(Duration.ofSeconds(MEMORY_WRITE_DELAY_SECONDS)) - .flatMap(ignored -> Mono.fromFuture(conversationServiceAsync.create()) - .flatMap(conv -> { - secondConvRef.set(conv.id()); - return Mono.fromFuture(openAIAsyncClient.responses().create( - ResponseCreateParams.builder() - .conversation(conv.id()) - .input("Please order my usual coffee") - .build())); - })) - .doOnNext(response -> System.out.println("Response: " + response.output())); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + // First conversation: teach a preference + return Mono.fromFuture(conversationServiceAsync.create()) + .flatMap(conv -> { + firstConvRef.set(conv.id()); + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .conversation(conv.id()) + .input("I prefer dark roast coffee") + .build()))); + }); + }) + .doOnNext(response -> System.out.println("First response received")) + .delayElement(Duration.ofSeconds(MEMORY_WRITE_DELAY_SECONDS)) + .flatMap(ignored -> { + // Second conversation: test memory recall + return Mono.fromFuture(conversationServiceAsync.create()) + .flatMap(conv -> { + secondConvRef.set(conv.id()); + return Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() + .conversation(conv.id()) + .input("Please order my usual coffee") + .build())); + }); + }) + .doOnNext(response -> System.out.println("Response: " + response.output())) .doFinally(signal -> { // Cleanup — await conversation deletes before proceeding try { @@ -138,6 +130,11 @@ public static void main(String[] args) throws Exception { } catch (Exception ignored) { // best-effort } + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()).block(); + System.out.println("Agent deleted"); + } try { memoryStoresClient.deleteMemoryStore(memoryStoreName); System.out.println("Memory store deleted"); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java index a8dcbcc18588a..0499f3bea07c3 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java @@ -5,19 +5,14 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.BetaMemoryStoresClient; -import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.MemorySearchPreviewTool; import com.azure.ai.agents.models.MemoryStoreDefaultDefinition; import com.azure.ai.agents.models.MemoryStoreDefaultOptions; import com.azure.ai.agents.models.MemoryStoreDetails; +import com.azure.ai.agents.BetaMemoryStoresClient; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -61,6 +56,7 @@ public static void main(String[] args) { String memoryStoreName = "my_memory_store"; String scope = "user_123"; + AgentVersionDetails agent = null; String firstConversationId = null; String followUpConversationId = null; @@ -87,52 +83,50 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - // Create the agent version and point the agent endpoint at the new version. - String agentName = "memory-search-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + agent = agentsClient.createAgentVersion("memory-search-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - // First conversation: teach the agent a preference - Conversation conversation = conversationService.create(); - firstConversationId = conversation.id(); - System.out.println("Created conversation (id: " + firstConversationId + ")"); + // First conversation: teach the agent a preference + Conversation conversation = conversationService.create(); + firstConversationId = conversation.id(); + System.out.println("Created conversation (id: " + firstConversationId + ")"); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .conversation(firstConversationId) .input("I prefer dark roast coffee") .build()); - System.out.println("Response: " + getResponseText(response)); + System.out.println("Response: " + getResponseText(response)); - // Wait for memories to be extracted and stored - System.out.println("Waiting for memories to be stored..."); - TimeUnit.SECONDS.sleep(MEMORY_WRITE_DELAY_SECONDS); + // Wait for memories to be extracted and stored + System.out.println("Waiting for memories to be stored..."); + TimeUnit.SECONDS.sleep(MEMORY_WRITE_DELAY_SECONDS); - // Second conversation: test memory recall - Conversation newConversation = conversationService.create(); - followUpConversationId = newConversation.id(); - System.out.println("Created new conversation (id: " + followUpConversationId + ")"); + // Second conversation: test memory recall + Conversation newConversation = conversationService.create(); + followUpConversationId = newConversation.id(); + System.out.println("Created new conversation (id: " + followUpConversationId + ")"); - Response followUpResponse = openAIClient.responses().create(ResponseCreateParams.builder() + Response followUpResponse = openAIClient.responses().create( + ResponseCreateParams.builder() .conversation(followUpConversationId) .input("Please order my usual coffee") .build()); - System.out.println("Response: " + getResponseText(followUpResponse)); - } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); - } + System.out.println("Response: " + getResponseText(followUpResponse)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("Sleep interrupted", e); } finally { deleteConversationQuietly(conversationService, firstConversationId); deleteConversationQuietly(conversationService, followUpConversationId); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } deleteMemoryStoreQuietly(memoryStoresClient, memoryStoreName); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java index b0d8058f1b564..ed362f1ae7220 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java @@ -6,6 +6,7 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiAnonymousAuthDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiTool; @@ -13,20 +14,14 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an OpenAPI tool @@ -48,6 +43,9 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("openapi-agent"); + + AtomicReference agentRef = new AtomicReference<>(); Map spec = OpenApiFunctionDefinition.readSpecFromFile( SampleUtils.getResourcePath("assets/httpbin_openapi.json")); @@ -61,27 +59,28 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant. Use the OpenAPI tool when asked to call an API.") .setTools(Collections.singletonList(openApiTool)); - String agentName = "openapi-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("openapi-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Call the API and tell me what it returns.") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java index 31c24629070b8..0015ca0c897e7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java @@ -6,6 +6,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiAnonymousAuthDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiTool; @@ -20,16 +21,8 @@ import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; -import java.util.Collections; import java.util.Map; /** @@ -71,33 +64,30 @@ public static void main(String[] args) throws Exception { .setInstructions("Use the OpenAPI tool for HTTP request metadata.") .setTools(Arrays.asList(new OpenApiTool(toolDefinition))); - String agentName = "openapi-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + AgentVersionDetails agentVersion = agentsClient.createAgentVersion("openapi-agent", agentDefinition); + System.out.println("Agent: " + agentVersion.getName() + ", version: " + agentVersion.getVersion()); + + // Create a conversation and add a user message + Conversation conversation = conversationService.create(); + conversationService.items().create( + ItemCreateParams.builder() + .conversationId(conversation.id()) + .addItem(EasyInputMessage.builder() + .role(EasyInputMessage.Role.USER) + .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") + .build()) + .build()); + try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - - // Create a conversation and add a user message - Conversation conversation = conversationService.create(); - conversationService.items().create( - ItemCreateParams.builder() - .conversationId(conversation.id()) - .addItem(EasyInputMessage.builder() - .role(EasyInputMessage.Role.USER) - .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") - .build()) - .build()); + SampleUtils.pinAgentVersion(agentsClient, agentVersion.getName(), agentVersion); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentVersion.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .maxOutputTokens(300L) - .conversation(conversation.id()) - .build()); + ResponseCreateParams.Builder options = ResponseCreateParams.builder() + .maxOutputTokens(300L); + + Response response = openAIClient.responses().create( + options.conversation(conversation.id()) + .build()); String text = response.output().stream() .filter(item -> item.isMessage()) @@ -111,7 +101,8 @@ public static void main(String[] args) throws Exception { System.out.println("Status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Response: " + text); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agentVersion.getName(), agentVersion.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java index 9e0367c29300a..81975db395b70 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java @@ -6,6 +6,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiAnonymousAuthDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiTool; @@ -20,16 +21,8 @@ import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; -import java.util.Collections; import java.util.Map; /** @@ -74,33 +67,30 @@ public static void main(String[] args) throws Exception { .setInstructions("Use the OpenAPI tool for HTTP request metadata.") .setTools(Arrays.asList(tool)); - String agentName = "openapi-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); + AgentVersionDetails agentVersion = agentsClient.createAgentVersion("openapi-agent", agentDefinition); + System.out.println("Agent: " + agentVersion.getName() + ", version: " + agentVersion.getVersion()); + + // Create a conversation and add a user message + Conversation conversation = conversationService.create(); + conversationService.items().create( + ItemCreateParams.builder() + .conversationId(conversation.id()) + .addItem(EasyInputMessage.builder() + .role(EasyInputMessage.Role.USER) + .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") + .build()) + .build()); + try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - - - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); - - // Create a conversation and add a user message - Conversation conversation = conversationService.create(); - conversationService.items().create( - ItemCreateParams.builder() - .conversationId(conversation.id()) - .addItem(EasyInputMessage.builder() - .role(EasyInputMessage.Role.USER) - .content("Use the OpenAPI tool and summarize the returned URL and origin in one sentence.") - .build()) - .build()); + SampleUtils.pinAgentVersion(agentsClient, agentVersion.getName(), agentVersion); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentVersion.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .maxOutputTokens(300L) - .conversation(conversation.id()) - .build()); + ResponseCreateParams.Builder options = ResponseCreateParams.builder() + .maxOutputTokens(300L); + + Response response = openAIClient.responses().create( + options.conversation(conversation.id()) + .build()); String text = response.output().stream() .filter(item -> item.isMessage()) @@ -114,7 +104,8 @@ public static void main(String[] args) throws Exception { System.out.println("Status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Response: " + text); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agentVersion.getName(), agentVersion.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java index 2e935da1457fa..b87c85dfa2b67 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java @@ -6,6 +6,7 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiProjectConnectionAuthDetails; import com.azure.ai.agents.models.OpenApiProjectConnectionSecurityScheme; @@ -14,20 +15,14 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates (using the async client) how to create an agent with an OpenAPI tool @@ -51,6 +46,9 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("openapi-connection-agent"); + + AtomicReference agentRef = new AtomicReference<>(); Map spec = OpenApiFunctionDefinition.readSpecFromFile( SampleUtils.getResourcePath("assets/httpbin_openapi.json")); @@ -67,27 +65,28 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(openApiTool)); - String agentName = "openapi-connection-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("openapi-connection-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Call the API and summarize the returned URL and origin.") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java index a3af2614604cf..28db28219b61c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java @@ -6,6 +6,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.OpenApiFunctionDefinition; import com.azure.ai.agents.models.OpenApiProjectConnectionAuthDetails; import com.azure.ai.agents.models.OpenApiProjectConnectionSecurityScheme; @@ -14,16 +15,9 @@ import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Map; @@ -77,25 +71,22 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(openApiTool)); - String agentName = "openapi-connection-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("openapi-connection-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Call the API and summarize the returned URL and origin.") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java index e20812c62603e..8b07214d79d47 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java @@ -5,25 +5,21 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.SharepointGroundingToolParameters; import com.azure.ai.agents.models.SharepointPreviewTool; import com.azure.ai.agents.models.ToolProjectConnection; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import java.time.Duration; import java.util.Arrays; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; /** * This sample demonstrates (using the async client) how to create an agent with the SharePoint Grounding tool @@ -47,6 +43,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("sharepoint-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create SharePoint grounding tool with connection configuration SharepointPreviewTool sharepointTool = new SharepointPreviewTool( @@ -60,27 +59,28 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can search through SharePoint documents.") .setTools(Collections.singletonList(sharepointTool)); - String agentName = "sharepoint-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("sharepoint-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("Find the latest project documentation in SharePoint") - .build())) - .doOnNext(response -> { - System.out.println("Response: " + response.output()); - }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + .build()))); + }) + .doOnNext(response -> { + System.out.println("Response: " + response.output()); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java index 6efbc92b29b40..99fc2c170a025 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.SharepointGroundingToolParameters; import com.azure.ai.agents.models.SharepointPreviewTool; import com.azure.ai.agents.models.ToolProjectConnection; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; import java.util.Arrays; @@ -63,25 +58,23 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can search through SharePoint documents.") .setTools(Collections.singletonList(sharepointTool)); - String agentName = "sharepoint-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + AgentVersionDetails agent = agentsClient.createAgentVersion("sharepoint-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + // Create a response + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .input("Find the latest project documentation in SharePoint") - .build()); + .build()); System.out.println("Response: " + response.output()); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + // Clean up + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java index 760e786e27a28..ccb812c363e2e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java @@ -5,25 +5,21 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WebSearchPreviewTool; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; import reactor.core.publisher.Mono; -import com.openai.client.OpenAIClientAsync; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create an agent with the Web Search tool @@ -45,6 +41,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("web-search-agent"); + + AtomicReference agentRef = new AtomicReference<>(); // Create a WebSearchPreviewTool WebSearchPreviewTool tool = new WebSearchPreviewTool(); @@ -54,36 +53,37 @@ public static void main(String[] args) { + "When asked to find information, use the web search tool to gather relevant data.") .setTools(Collections.singletonList(tool)); - String agentName = "web-search-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion("web-search-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .input("What are the latest trends in renewable energy?") - .build())) - .doOnNext(response -> { - for (ResponseOutputItem outputItem : response.output()) { - if (outputItem.message().isPresent()) { - ResponseOutputMessage message = outputItem.message().get(); - message.content().forEach(content -> { - content.outputText().ifPresent(text -> { - System.out.println("Assistant: " + text.text()); - }); - }); - } - } + .build()))); + }) + .doOnNext(response -> { + for (ResponseOutputItem outputItem : response.output()) { + if (outputItem.message().isPresent()) { + ResponseOutputMessage message = outputItem.message().get(); + message.content().forEach(content -> { + content.outputText().ifPresent(text -> { + System.out.println("Assistant: " + text.text()); + }); }); - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + } + } + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(30)) .block(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java index 0e5caf6ec7044..4f38eacf2d3b2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WebSearchPreviewTool; import com.azure.core.util.Configuration; @@ -14,13 +16,6 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import com.openai.models.responses.ResponseOutputMessage; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -45,32 +40,31 @@ public static void main(String[] args) { AgentsClient agentsClient = builder.buildAgentsClient(); - // BEGIN: com.azure.ai.agents.define_web_search - // Create a WebSearchPreviewTool - WebSearchPreviewTool tool = new WebSearchPreviewTool(); - // END: com.azure.ai.agents.define_web_search - - // Create the agent definition with Web Search tool enabled - PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) - .setInstructions("You are a helpful assistant that can perform web searches to find information. " - + "When asked to find information, use the web search tool to gather relevant data.") - .setTools(Collections.singletonList(tool)); + AgentVersionDetails agent = null; - String agentName = "web-search-agent"; - AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); + // BEGIN: com.azure.ai.agents.define_web_search + // Create a WebSearchPreviewTool + WebSearchPreviewTool tool = new WebSearchPreviewTool(); + // END: com.azure.ai.agents.define_web_search + // Create the agent definition with Web Search tool enabled + PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) + .setInstructions("You are a helpful assistant that can perform web searches to find information. " + + "When asked to find information, use the web search tool to gather relevant data.") + .setTools(Collections.singletonList(tool)); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + agent = agentsClient.createAgentVersion("web-search-agent", agentDefinition); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() - .input("What are the latest trends in renewable energy?") - .build()); + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); + + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() + .input("What are the latest trends in renewable energy?") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -84,7 +78,10 @@ public static void main(String[] args) { } } } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + if (agent != null) { + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); + } } } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java index 5d213caecba76..ff097e89e29d7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java @@ -5,6 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WorkIqPreviewTool; import com.azure.core.util.Configuration; @@ -15,13 +17,6 @@ import com.openai.models.responses.ResponseOutputMessage; import com.openai.models.responses.ToolChoiceOptions; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.time.Duration; import java.util.Collections; @@ -57,6 +52,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); WorkIqPreviewTool workIqTool = new WorkIqPreviewTool(workIqConnectionId); @@ -66,34 +62,38 @@ public static void main(String[] args) { + "Teams messages, and other Microsoft 365 content.") .setTools(Collections.singletonList(workIqTool)); - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - return Mono.fromFuture(openAIAsyncClient.responses().create(ResponseCreateParams.builder() + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) + .flatMap(agent -> Mono.usingWhen( + Mono.just(agent), + createdAgent -> { + System.out.printf("Agent created: %s (version %s)%n", + createdAgent.getName(), createdAgent.getVersion()); + + return SampleUtils.pinAgentVersion(agentsAsyncClient, createdAgent.getName(), createdAgent) + .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( + ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) .input(userInput) - .build())) + .build()))) .doOnNext(response -> { System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Agent response: " + getResponseText(response)); }); }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + createdAgent -> deleteAgentVersion(agentsAsyncClient, createdAgent), + (createdAgent, error) -> deleteAgentVersion(agentsAsyncClient, createdAgent), + createdAgent -> deleteAgentVersion(agentsAsyncClient, createdAgent))) .doOnError(error -> System.err.println("Error: " + error.getMessage())) .timeout(Duration.ofSeconds(300)) .block(); } + private static Mono deleteAgentVersion(AgentsAsyncClient agentsAsyncClient, AgentVersionDetails agent) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(unused -> System.out.println("Agent deleted")); + } + private static String getResponseText(Response response) { if (response == null || response.output().isEmpty()) { return ""; diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java index b6007e61beaa4..8a5ca086192e1 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java @@ -5,22 +5,17 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.SampleUtils; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.WorkIqPreviewTool; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClient; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputMessage; import com.openai.models.responses.ToolChoiceOptions; -import com.openai.client.OpenAIClient; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; @@ -68,25 +63,23 @@ public static void main(String[] args) { .setTools(Collections.singletonList(workIqTool)); AgentVersionDetails agent = agentsClient.createAgentVersion(agentName, agentDefinition); - try { - agentsClient.updateAgentDetails(agentName, new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))); - + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentName); + try { + SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); - Response response = openAIClient.responses().create(ResponseCreateParams.builder() + Response response = openAIClient.responses().create( + ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) .input(userInput) - .build()); + .build()); System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); System.out.println("Agent response: " + getResponseText(response)); } finally { - agentsClient.deleteAgentVersion(agentName, agent.getVersion()); + agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion()); + System.out.println("Agent deleted"); } } From b9ac651cc9e80811744df35be6fd36bf5f348a9e Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 11:29:14 -0700 Subject: [PATCH 04/17] revert some streaming --- .../CodeInterpreterStreamingAsync.java | 104 +++++++-------- .../streaming/FunctionCallStreamingAsync.java | 118 +++++++++--------- 2 files changed, 111 insertions(+), 111 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java index 122ce1ca83406..b1c5145a1c313 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java @@ -5,23 +5,21 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.ResponsesAsyncClient; +import com.azure.ai.agents.models.AgentReference; +import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; -import com.openai.client.OpenAIClientAsync; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to stream a response from an agent configured with the @@ -44,6 +42,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); + + AtomicReference agentRef = new AtomicReference<>(); // Create a CodeInterpreterTool - an Azure-specific tool for executing Python code CodeInterpreterTool tool = new CodeInterpreterTool(); @@ -54,54 +55,53 @@ public static void main(String[] args) { + "When asked to perform calculations, use the code interpreter to run Python code.") .setTools(Collections.singletonList(tool)); - // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, - // so responses.createStreaming(...) below does not need to send an agent_reference in its body. - String agentName = "code-interpreter-streaming-async-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); + agentsAsyncClient.createAgentVersion("code-interpreter-streaming-async-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + AgentReference agentReference = new AgentReference(agent.getName()) + .setVersion(agent.getVersion()); - // BEGIN: com.azure.ai.agents.streaming.code_interpreter_async - // Stream response asynchronously with Code Interpreter - ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + // BEGIN: com.azure.ai.agents.streaming.code_interpreter_async + // Stream response asynchronously with Code Interpreter + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - return Mono.fromFuture(openAIAsyncClient.responses() - .createStreaming(ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers using Python.") - .build()) - .subscribe(event -> { - responseAccumulator.accumulate(event); - // Print text deltas as they arrive - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - // Observe code interpreter progress events - event.codeInterpreterCallInProgress() - .ifPresent(e -> System.out.println("\n[Code interpreter running...]")); - event.codeInterpreterCallCodeDelta() - .ifPresent(e -> System.out.print(e.delta())); - event.codeInterpreterCallCompleted() - .ifPresent(e -> System.out.println("\n[Code interpreter completed]")); - }) - .onCompleteFuture()) - .doOnSuccess(unused -> { - System.out.println(); + return responsesAsyncClient.createStreamingAzureResponse( + new AzureCreateResponseOptions().setAgentReference(agentReference), + ResponseCreateParams.builder() + .input("Calculate the first 10 prime numbers using Python.")) + .doOnNext(event -> { + responseAccumulator.accumulate(event); + // Print text deltas as they arrive + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + // Observe code interpreter progress events + event.codeInterpreterCallInProgress() + .ifPresent(e -> System.out.println("\n[Code interpreter running...]")); + event.codeInterpreterCallCodeDelta() + .ifPresent(e -> System.out.print(e.delta())); + event.codeInterpreterCallCompleted() + .ifPresent(e -> System.out.println("\n[Code interpreter completed]")); + }) + .then(Mono.fromCallable(() -> { + System.out.println(); - // Access the complete accumulated response - Response response = responseAccumulator.response(); - System.out.println("\nResponse ID: " + response.id()); - }); - // END: com.azure.ai.agents.streaming.code_interpreter_async - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + // Access the complete accumulated response + Response response = responseAccumulator.response(); + System.out.println("\nResponse ID: " + response.id()); + // END: com.azure.ai.agents.streaming.code_interpreter_async + return response; + })); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .block(); } } diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java index ff85aeb39e596..c824adaca8e02 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java @@ -5,29 +5,27 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.ResponsesAsyncClient; +import com.azure.ai.agents.models.AgentReference; +import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; -import com.openai.client.OpenAIClientAsync; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseOutputItem; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to stream a response from an agent configured with a @@ -50,6 +48,9 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); + + AtomicReference agentRef = new AtomicReference<>(); // Define a function tool with parameter schema Map locationProp = new LinkedHashMap<>(); @@ -79,58 +80,57 @@ public static void main(String[] args) { + "When asked about the weather, use the get_weather function.") .setTools(Collections.singletonList(tool)); - // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, - // so responses.createStreaming(...) below does not need to send an agent_reference in its body. - String agentName = "function-streaming-async-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); - - // BEGIN: com.azure.ai.agents.streaming.function_call_async - // Stream response asynchronously with function tool - ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - - return Mono.fromFuture(openAIAsyncClient.responses() - .createStreaming(ResponseCreateParams.builder() - .input("What's the weather like in Seattle?") - .build()) - .subscribe(event -> { - responseAccumulator.accumulate(event); - // Print text deltas as they arrive - event.outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta())); - // Print function call argument deltas as they arrive - event.functionCallArgumentsDelta() - .ifPresent(argEvent -> System.out.print(argEvent.delta())); - }) - .onCompleteFuture()) - .doOnSuccess(unused -> { - System.out.println(); - - // Access the final response and inspect function calls - Response response = responseAccumulator.response(); - for (ResponseOutputItem outputItem : response.output()) { - outputItem.functionCall().ifPresent(functionCall -> { - System.out.println("\n--- Function Tool Call ---"); - System.out.println("Call ID: " + functionCall.callId()); - System.out.println("Function Name: " + functionCall.name()); - System.out.println("Arguments: " + functionCall.arguments()); - System.out.println("Status: " + functionCall.status()); - }); - } - }); - // END: com.azure.ai.agents.streaming.function_call_async - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + agentsAsyncClient.createAgentVersion("function-streaming-async-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); + + AgentReference agentReference = new AgentReference(agent.getName()) + .setVersion(agent.getVersion()); + + // BEGIN: com.azure.ai.agents.streaming.function_call_async + // Stream response asynchronously with function tool + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + + return responsesAsyncClient.createStreamingAzureResponse( + new AzureCreateResponseOptions().setAgentReference(agentReference), + ResponseCreateParams.builder() + .input("What's the weather like in Seattle?")) + .doOnNext(event -> { + responseAccumulator.accumulate(event); + // Print text deltas as they arrive + event.outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta())); + // Print function call argument deltas as they arrive + event.functionCallArgumentsDelta() + .ifPresent(argEvent -> System.out.print(argEvent.delta())); + }) + .then(Mono.fromCallable(() -> { + System.out.println(); + + // Access the final response and inspect function calls + Response response = responseAccumulator.response(); + for (ResponseOutputItem outputItem : response.output()) { + outputItem.functionCall().ifPresent(functionCall -> { + System.out.println("\n--- Function Tool Call ---"); + System.out.println("Call ID: " + functionCall.callId()); + System.out.println("Function Name: " + functionCall.name()); + System.out.println("Arguments: " + functionCall.arguments()); + System.out.println("Status: " + functionCall.status()); + }); + } + // END: com.azure.ai.agents.streaming.function_call_async + return response; + })); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .block(); } } From 2209fa2f1fc5292eab9a66ce2c1a253ce8956a18 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 13:59:29 -0700 Subject: [PATCH 05/17] try handle openai streaming --- sdk/ai/azure-ai-agents/README.md | 37 ++++---- .../streaming/SimpleStreamingAsync.java | 87 +++++++++++-------- 2 files changed, 71 insertions(+), 53 deletions(-) diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index 2f2243eacffd6..193b967e8277b 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -806,25 +806,28 @@ See the full samples in [SimpleStreamingSync.java](https://github.com/Azure/azur The asynchronous streaming methods return `Flux`, integrating naturally with Reactor pipelines: ```java com.azure.ai.agents.streaming.simple_async -// Use ResponseAccumulator to collect streamed events into a final Response -ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); +// OpenAI streaming events arrive through callbacks. This Mono only tracks terminal completion. +Mono streamingCompletion = Mono.defer(() -> { + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( + ResponseCreateParams.builder() + .input("Tell me a short story about a brave explorer.") + .build()); -// Stream response asynchronously - text is printed as each chunk arrives -return Mono.fromFuture(openAIAsyncClient.responses() - .createStreaming(ResponseCreateParams.builder() - .input("Tell me a short story about a brave explorer.") - .build()) - .subscribe(event -> responseAccumulator.accumulate(event) + stream.subscribe(event -> responseAccumulator.accumulate(event) .outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta()))) - .onCompleteFuture()) - .doOnSuccess(unused -> { - System.out.println(); // newline after streamed text - - // Access the complete accumulated response - Response response = responseAccumulator.response(); - System.out.println("\nResponse ID: " + response.id()); - }); + .ifPresent(textEvent -> System.out.print(textEvent.delta()))); + + return Mono.fromFuture(stream.onCompleteFuture()) + .doOnSuccess(unused -> { + System.out.println(); // newline after streamed text + + // Access the complete accumulated response + Response response = responseAccumulator.response(); + System.out.println("\nResponse ID: " + response.id()); + }) + .doFinally(signal -> stream.close()); +}); ``` See the full samples in [SimpleStreamingAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java), [FunctionCallStreamingAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java), and [CodeInterpreterStreamingAsync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java). diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java index 371868bb54faf..caa8e510aaa85 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java @@ -5,22 +5,26 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; +import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.models.ProtocolConfiguration; +import com.azure.ai.agents.models.ResponsesProtocolConfiguration; +import com.azure.ai.agents.models.UpdateAgentDetailsOptions; +import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; +import com.openai.core.http.AsyncStreamResponse; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; +import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; -import com.azure.ai.agents.models.AgentEndpointConfig; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; /** * This sample demonstrates how to create a streaming response using the asynchronous client. @@ -43,49 +47,60 @@ public static void main(String[] args) { AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); + AtomicReference agentRef = new AtomicReference<>(); + // Create an agent PromptAgentDefinition agentDefinition = new PromptAgentDefinition(model) .setInstructions("You are a helpful assistant that tells short, engaging stories."); - // Create the agent version and pin the agent endpoint to it. The endpoint URL identifies the agent, - // so responses.createStreaming(...) below does not need to send an agent_reference in its body. - String agentName = "streaming-async-agent"; - Mono.usingWhen( - agentsAsyncClient.createAgentVersion(agentName, agentDefinition) - .flatMap(agent -> agentsAsyncClient.updateAgentDetails(agentName, - new UpdateAgentDetailsOptions().setAgentEndpoint( - new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())))) - .thenReturn(agent)), - agent -> { - OpenAIClientAsync openAIAsyncClient - = builder.buildAgentScopedOpenAIAsyncClient(agentName); + agentsAsyncClient.createAgentVersion("streaming-async-agent", agentDefinition) + .flatMap(agent -> { + agentRef.set(agent); + System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - // BEGIN: com.azure.ai.agents.streaming.simple_async - // Use ResponseAccumulator to collect streamed events into a final Response - ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + AgentEndpointConfig endpointConfig = new AgentEndpointConfig() + .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agent.getName()); - // Stream response asynchronously - text is printed as each chunk arrives - return Mono.fromFuture(openAIAsyncClient.responses() - .createStreaming(ResponseCreateParams.builder() + // BEGIN: com.azure.ai.agents.streaming.simple_async + // OpenAI streaming events arrive through callbacks. This Mono only tracks terminal completion. + Mono streamingCompletion = Mono.defer(() -> { + ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); + AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( + ResponseCreateParams.builder() .input("Tell me a short story about a brave explorer.") - .build()) - .subscribe(event -> responseAccumulator.accumulate(event) - .outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta()))) - .onCompleteFuture()) + .build()); + + stream.subscribe(event -> responseAccumulator.accumulate(event) + .outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta()))); + + return Mono.fromFuture(stream.onCompleteFuture()) .doOnSuccess(unused -> { System.out.println(); // newline after streamed text // Access the complete accumulated response Response response = responseAccumulator.response(); System.out.println("\nResponse ID: " + response.id()); - }); - // END: com.azure.ai.agents.streaming.simple_async - }, - agent -> agentsAsyncClient.deleteAgentVersion(agentName, agent.getVersion())) + }) + .doFinally(signal -> stream.close()); + }); + // END: com.azure.ai.agents.streaming.simple_async + + return agentsAsyncClient.updateAgentDetails(agent.getName(), + new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)) + .then(streamingCompletion); + }) + .then(Mono.defer(() -> { + AgentVersionDetails agent = agentRef.get(); + if (agent != null) { + return agentsAsyncClient.deleteAgentVersion(agent.getName(), agent.getVersion()) + .doOnSuccess(v -> System.out.println("Agent deleted")); + } + return Mono.empty(); + })) .block(); } } From 53d056852ad9cd395dccc31437d528e3f02d0536 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 14:48:50 -0700 Subject: [PATCH 06/17] update util --- .../azure/ai/agents/MemorySearchAgent.java | 13 +---------- .../ai/agents/MultipleAgentsConversation.java | 23 ++----------------- .../java/com/azure/ai/agents/SampleUtils.java | 22 +++++++++--------- .../CodeInterpreterStreamingSync.java | 14 ++--------- .../streaming/FunctionCallStreamingSync.java | 14 ++--------- .../streaming/SimpleStreamingAsync.java | 16 ++----------- .../agents/streaming/SimpleStreamingSync.java | 16 ++----------- .../ai/agents/tools/AgentToAgentAsync.java | 2 +- .../ai/agents/tools/AgentToAgentSync.java | 2 +- .../ai/agents/tools/AzureAISearchAsync.java | 2 +- .../ai/agents/tools/AzureAISearchSync.java | 2 +- .../ai/agents/tools/AzureFunctionAsync.java | 2 +- .../ai/agents/tools/AzureFunctionSync.java | 2 +- .../agents/tools/BingCustomSearchAsync.java | 2 +- .../ai/agents/tools/BingCustomSearchSync.java | 2 +- .../ai/agents/tools/BingGroundingAsync.java | 2 +- .../ai/agents/tools/BingGroundingSync.java | 2 +- .../agents/tools/BrowserAutomationAsync.java | 2 +- .../agents/tools/BrowserAutomationSync.java | 2 +- .../ai/agents/tools/CodeInterpreterAsync.java | 2 +- .../ai/agents/tools/CodeInterpreterSync.java | 2 +- .../ai/agents/tools/ComputerUseAsync.java | 2 +- .../ai/agents/tools/ComputerUseSync.java | 2 +- .../tools/CustomCodeInterpreterAsync.java | 2 +- .../tools/CustomCodeInterpreterSync.java | 2 +- .../azure/ai/agents/tools/FabricAsync.java | 2 +- .../azure/ai/agents/tools/FabricIQAsync.java | 2 +- .../azure/ai/agents/tools/FabricIQSync.java | 2 +- .../com/azure/ai/agents/tools/FabricSync.java | 2 +- .../ai/agents/tools/FunctionCallAsync.java | 2 +- .../ai/agents/tools/FunctionCallSync.java | 2 +- .../ai/agents/tools/ImageGenerationAsync.java | 2 +- .../ai/agents/tools/ImageGenerationSync.java | 2 +- .../com/azure/ai/agents/tools/McpAsync.java | 2 +- .../com/azure/ai/agents/tools/McpSync.java | 2 +- .../agents/tools/McpWithConnectionAsync.java | 2 +- .../agents/tools/McpWithConnectionSync.java | 2 +- .../ai/agents/tools/MemorySearchAsync.java | 2 +- .../ai/agents/tools/MemorySearchSync.java | 2 +- .../azure/ai/agents/tools/OpenApiAsync.java | 2 +- .../azure/ai/agents/tools/OpenApiSample.java | 2 +- .../azure/ai/agents/tools/OpenApiSync.java | 2 +- .../tools/OpenApiWithConnectionAsync.java | 2 +- .../tools/OpenApiWithConnectionSync.java | 2 +- .../tools/SharePointGroundingAsync.java | 2 +- .../agents/tools/SharePointGroundingSync.java | 2 +- .../azure/ai/agents/tools/WebSearchAsync.java | 2 +- .../azure/ai/agents/tools/WebSearchSync.java | 2 +- .../azure/ai/agents/tools/WorkIQAsync.java | 2 +- .../com/azure/ai/agents/tools/WorkIQSync.java | 2 +- 50 files changed, 65 insertions(+), 139 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java index 1b182360f80ed..4178b1b7ab3c7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MemorySearchAgent.java @@ -3,18 +3,12 @@ package com.azure.ai.agents; -import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.MemorySearchPreviewTool; import com.azure.ai.agents.models.MemoryStoreDefaultDefinition; import com.azure.ai.agents.models.MemoryStoreDefaultOptions; import com.azure.ai.agents.models.MemoryStoreDetails; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.exception.ResourceNotFoundException; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -78,12 +72,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion(agentName, agentDefinition); System.out.printf("Agent created (id: %s, version: %s)\n", agent.getId(), agent.getVersion()); - AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); - agentsClient.updateAgentDetails(agent.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java index 0632de7e5a071..e050acc4eff29 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/MultipleAgentsConversation.java @@ -3,14 +3,8 @@ package com.azure.ai.agents; -import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClient; @@ -22,8 +16,6 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; -import java.util.Collections; - /** * This sample how multiple agents can consume a centralized context source (conversation) and provide different responses * based on it. @@ -56,19 +48,8 @@ public static void main(String[] args) { AgentVersionDetails agent1 = createPromptAgent(agentsClient, model, "weather-agent-1"); AgentVersionDetails agent2 = createPromptAgent(agentsClient, model, "weather-agent-2"); - AgentEndpointConfig agent1EndpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent1.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); - agentsClient.updateAgentDetails(agent1.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(agent1EndpointConfig)); - - AgentEndpointConfig agent2EndpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent2.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); - agentsClient.updateAgentDetails(agent2.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(agent2EndpointConfig)); + SampleUtils.pinAgentVersion(agentsClient, agent1); + SampleUtils.pinAgentVersion(agentsClient, agent2); OpenAIClient agent1Client = builder.buildAgentScopedOpenAIClient(agent1.getName()); OpenAIClient agent2Client = builder.buildAgentScopedOpenAIClient(agent2.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java index f6e7f1dadcd02..e36d3a485b4b2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java @@ -26,24 +26,24 @@ public class SampleUtils { * Pins an agent endpoint to a specific agent version and enables the OpenAI Responses protocol. * * @param agentsClient the agents client - * @param agentName the agent name - * @param agent the agent version to pin + * @param versionDetails the agent version to pin + * @return the updated agent details */ - public static void pinAgentVersion(AgentsClient agentsClient, String agentName, AgentVersionDetails agent) { - agentsClient.updateAgentDetails(agentName, createPinnedEndpointOptions(agent)); + public static AgentDetails pinAgentVersion(AgentsClient agentsClient, AgentVersionDetails versionDetails) { + return agentsClient.updateAgentDetails(versionDetails.getName(), createPinnedEndpointOptions(versionDetails)); } /** * Pins an agent endpoint to a specific agent version and enables the OpenAI Responses protocol. * * @param agentsAsyncClient the asynchronous agents client - * @param agentName the agent name - * @param agent the agent version to pin + * @param versionDetails the agent version to pin * @return a publisher containing the updated agent details */ - public static Mono pinAgentVersion(AgentsAsyncClient agentsAsyncClient, String agentName, - AgentVersionDetails agent) { - return agentsAsyncClient.updateAgentDetails(agentName, createPinnedEndpointOptions(agent)); + public static Mono pinAgentVersion(AgentsAsyncClient agentsAsyncClient, + AgentVersionDetails versionDetails) { + return agentsAsyncClient.updateAgentDetails(versionDetails.getName(), + createPinnedEndpointOptions(versionDetails)); } /** @@ -73,10 +73,10 @@ public static Path getResourcePath(String fileName) { throw new RuntimeException("Sample resource file not found: " + fileName); } - private static UpdateAgentDetailsOptions createPinnedEndpointOptions(AgentVersionDetails agent) { + private static UpdateAgentDetailsOptions createPinnedEndpointOptions(AgentVersionDetails versionDetails) { AgentEndpointConfig endpointConfig = new AgentEndpointConfig() .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + new FixedRatioVersionSelectionRule(100).setAgentVersion(versionDetails.getVersion())))) .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); return new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java index 113339713a313..4c4c3df5ca9da 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingSync.java @@ -5,15 +5,10 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClient; @@ -62,12 +57,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("code-interpreter-streaming-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); - agentsClient.updateAgentDetails(agent.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.code_interpreter_sync diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java index 94239884d144a..1b90d311e1cac 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingSync.java @@ -5,15 +5,10 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; @@ -87,12 +82,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("function-streaming-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); - agentsClient.updateAgentDetails(agent.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.function_call_sync diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java index caa8e510aaa85..2f8c8982308f9 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java @@ -5,14 +5,9 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; @@ -23,7 +18,6 @@ import com.openai.models.responses.ResponseStreamEvent; import reactor.core.publisher.Mono; -import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; /** @@ -58,10 +52,6 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.simple_async @@ -89,9 +79,7 @@ public static void main(String[] args) { }); // END: com.azure.ai.agents.streaming.simple_async - return agentsAsyncClient.updateAgentDetails(agent.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)) - .then(streamingCompletion); + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent).then(streamingCompletion); }) .then(Mono.defer(() -> { AgentVersionDetails agent = agentRef.get(); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java index ef2f87b38c499..1f996a820b76b 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingSync.java @@ -5,14 +5,9 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.models.AgentEndpointConfig; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; -import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; -import com.azure.ai.agents.models.ProtocolConfiguration; -import com.azure.ai.agents.models.ResponsesProtocolConfiguration; -import com.azure.ai.agents.models.UpdateAgentDetailsOptions; -import com.azure.ai.agents.models.VersionSelector; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClient; @@ -22,8 +17,6 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.models.responses.ResponseStreamEvent; -import java.util.Collections; - /** * This sample demonstrates how to create a streaming response using the synchronous client. * Text is printed as it arrives rather than waiting for the full response. @@ -55,12 +48,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("streaming-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) - .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); - agentsClient.updateAgentDetails(agent.getName(), - new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.simple_sync diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java index 0a65efb73d111..5fae1825ad023 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java @@ -58,7 +58,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("What can the secondary agent do?") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java index ad3a30bfb3a9a..855145e3d6c16 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentSync.java @@ -57,7 +57,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java index 4f16e064679f2..17ac4b657e6c5 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java @@ -70,7 +70,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Search for information about Azure AI services") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java index 9c318dc39ff02..a2ade1bb0b036 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchSync.java @@ -69,7 +69,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java index 7c10fc2c4e795..1ec6e97364840 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java @@ -89,7 +89,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java index 7391265dc9ae6..8f194cdc09d84 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java @@ -89,7 +89,7 @@ public static void main(String[] args) { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); try { - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java index 3514090b702ba..bd6193d39bb89 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java @@ -66,7 +66,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Search for the latest Azure AI documentation") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java index ae49955179217..5b41507075151 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchSync.java @@ -69,7 +69,7 @@ public static void main(String[] args) { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); try { - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java index 584b4680cdb65..af4cebe02bfd4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java @@ -63,7 +63,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("What are the latest developments in AI?") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java index 3a7dcf3428210..3f56273dafada 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingSync.java @@ -62,7 +62,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java index aa612e04121ca..fa930daf76825 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java @@ -62,7 +62,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Navigate to microsoft.com and summarize the main content") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java index 4cb64445f1d5e..6bf4551134d3c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationSync.java @@ -61,7 +61,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java index 96c9ca4cb9cb7..959720fdab16e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java @@ -59,7 +59,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Calculate the first 10 prime numbers and show me the Python code you used.") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java index 78fbfcaca227f..42f7ca99800a8 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterSync.java @@ -58,7 +58,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("code-interpreter-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java index 229aa4b7d2f3a..415f56de9b85a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java @@ -134,7 +134,7 @@ public static void main(String[] args) { System.out.println("Starting computer automation session (initial screenshot: cua_browser_search.png)..."); // Send initial request - return SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .inputOfResponse(initialInput) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java index e2ae5df6fbf6e..d2f9f82f8b1a3 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java @@ -102,7 +102,7 @@ public static void main(String[] args) { System.out.printf("Agent created (id: %s, name: %s, version: %s)%n", agent.getId(), agent.getName(), agent.getVersion()); - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // Initial request with screenshot - start with Bing search page diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java index 1df24309a895f..d41e340aa8838 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java @@ -61,7 +61,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Calculate the factorial of 10 using Python.") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java index a6a50871b2f85..8e3a4a299ddfc 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterSync.java @@ -59,7 +59,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java index d740e55c1f13b..7c9ac4206938c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java @@ -64,7 +64,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Query the latest sales data from Microsoft Fabric") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java index 33f2075fe8496..3f92a93e72a86 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQAsync.java @@ -62,7 +62,7 @@ public static void main(String[] args) { agent -> { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input(userInput) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java index e5925603127c2..21b56b0014512 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricIQSync.java @@ -62,7 +62,7 @@ public static void main(String[] args) { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); try { - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java index 3045977a7414d..f58dac20752ec 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricSync.java @@ -63,7 +63,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java index ffe0106d9ec19..0ac062513660c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java @@ -85,7 +85,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("What's the weather like in Seattle?") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java index 32d9ee0592af4..bd15b650bf322 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallSync.java @@ -81,7 +81,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("function-call-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java index c03fe9dde1778..964db2c90f72c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java @@ -62,7 +62,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Generate an image of a sunset over a mountain range") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java index 68e8604552815..ac209de553f3b 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationSync.java @@ -61,7 +61,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java index f457ef48839d1..24656e4886278 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java @@ -67,7 +67,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Please summarize the Azure REST API specifications Readme") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java index d302a2918f3cc..183825ae54233 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpSync.java @@ -66,7 +66,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("mcp-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java index b46607f57f8b2..7d2da3867bfd8 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java @@ -63,7 +63,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("What is my username in GitHub profile?") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java index d1f6b23100605..67ccd8aab716b 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionSync.java @@ -68,7 +68,7 @@ public static void main(String[] args) { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); try { - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // Create a conversation for context diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java index 6003da2c1b46e..bd788045d46e0 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java @@ -93,7 +93,7 @@ public static void main(String[] args) throws Exception { return Mono.fromFuture(conversationServiceAsync.create()) .flatMap(conv -> { firstConvRef.set(conv.id()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .conversation(conv.id()) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java index 0499f3bea07c3..e845b35c56949 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchSync.java @@ -86,7 +86,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("memory-search-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java index ed362f1ae7220..b755d6e48cb92 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java @@ -64,7 +64,7 @@ public static void main(String[] args) throws Exception { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Call the API and tell me what it returns.") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java index 0015ca0c897e7..9fc2d8ad1f17d 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java @@ -79,7 +79,7 @@ public static void main(String[] args) throws Exception { .build()); try { - SampleUtils.pinAgentVersion(agentsClient, agentVersion.getName(), agentVersion); + SampleUtils.pinAgentVersion(agentsClient, agentVersion); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentVersion.getName()); ResponseCreateParams.Builder options = ResponseCreateParams.builder() diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java index 81975db395b70..67100967c0668 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java @@ -82,7 +82,7 @@ public static void main(String[] args) throws Exception { .build()); try { - SampleUtils.pinAgentVersion(agentsClient, agentVersion.getName(), agentVersion); + SampleUtils.pinAgentVersion(agentsClient, agentVersion); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentVersion.getName()); ResponseCreateParams.Builder options = ResponseCreateParams.builder() diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java index b87c85dfa2b67..c2e2df23733b1 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java @@ -70,7 +70,7 @@ public static void main(String[] args) throws Exception { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Call the API and summarize the returned URL and origin.") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java index 28db28219b61c..28ea194f8f769 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionSync.java @@ -75,7 +75,7 @@ public static void main(String[] args) throws Exception { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); try { - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java index 8b07214d79d47..24a96cadcd7a6 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java @@ -64,7 +64,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("Find the latest project documentation in SharePoint") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java index 99fc2c170a025..6cdeb0b93506f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingSync.java @@ -63,7 +63,7 @@ public static void main(String[] args) { try { // Create a response - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java index ccb812c363e2e..bf02bbbc7c28a 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java @@ -58,7 +58,7 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, agent.getName(), agent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .input("What are the latest trends in renewable energy?") diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java index 4f38eacf2d3b2..7e3897ab3bfba 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchSync.java @@ -57,7 +57,7 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("web-search-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java index ff097e89e29d7..ace5fe457f859 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java @@ -69,7 +69,7 @@ public static void main(String[] args) { System.out.printf("Agent created: %s (version %s)%n", createdAgent.getName(), createdAgent.getVersion()); - return SampleUtils.pinAgentVersion(agentsAsyncClient, createdAgent.getName(), createdAgent) + return SampleUtils.pinAgentVersion(agentsAsyncClient, createdAgent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( ResponseCreateParams.builder() .toolChoice(ToolChoiceOptions.REQUIRED) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java index 8a5ca086192e1..255911e1e6ed5 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQSync.java @@ -66,7 +66,7 @@ public static void main(String[] args) { System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); try { - SampleUtils.pinAgentVersion(agentsClient, agent.getName(), agent); + SampleUtils.pinAgentVersion(agentsClient, agent); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); Response response = openAIClient.responses().create( From c4938ef6f5bd7bca1b18aab0453da36c21c70c9d Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 14:53:47 -0700 Subject: [PATCH 07/17] cleanup --- .../java/com/azure/ai/agents/tools/AgentToAgentAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/AzureAISearchAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/AzureFunctionAsync.java | 5 +++-- .../com/azure/ai/agents/tools/BingCustomSearchAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/BingGroundingAsync.java | 5 +++-- .../com/azure/ai/agents/tools/BrowserAutomationAsync.java | 5 +++-- .../com/azure/ai/agents/tools/CodeInterpreterAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/ComputerUseAsync.java | 7 ++++--- .../java/com/azure/ai/agents/tools/ComputerUseSync.java | 2 +- .../azure/ai/agents/tools/CustomCodeInterpreterAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/FabricAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/FunctionCallAsync.java | 5 +++-- .../com/azure/ai/agents/tools/ImageGenerationAsync.java | 5 +++-- .../samples/java/com/azure/ai/agents/tools/McpAsync.java | 5 +++-- .../com/azure/ai/agents/tools/McpWithConnectionAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/MemorySearchAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/OpenApiAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/OpenApiSample.java | 7 +++---- .../java/com/azure/ai/agents/tools/OpenApiSync.java | 7 +++---- .../azure/ai/agents/tools/OpenApiWithConnectionAsync.java | 5 +++-- .../azure/ai/agents/tools/SharePointGroundingAsync.java | 5 +++-- .../java/com/azure/ai/agents/tools/WebSearchAsync.java | 5 +++-- 22 files changed, 65 insertions(+), 48 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java index 5fae1825ad023..fdc6b54a3ae22 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AgentToAgentAsync.java @@ -34,6 +34,7 @@ public class AgentToAgentAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "a2a-agent"; String a2aConnectionId = Configuration.getGlobalConfiguration().get("A2A_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -41,7 +42,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("a2a-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -53,7 +54,7 @@ public static void main(String[] args) { .setInstructions("You are a coordinator agent that can communicate with other agents.") .setTools(Collections.singletonList(a2aTool)); - agentsAsyncClient.createAgentVersion("a2a-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java index 17ac4b657e6c5..164f50c0b2c1c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureAISearchAsync.java @@ -38,6 +38,7 @@ public class AzureAISearchAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "ai-search-agent"; String connectionId = Configuration.getGlobalConfiguration().get("AZURE_AI_SEARCH_CONNECTION_ID"); String indexName = Configuration.getGlobalConfiguration().get("AI_SEARCH_INDEX_NAME"); @@ -46,7 +47,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("ai-search-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -65,7 +66,7 @@ public static void main(String[] args) { + "Always provide citations for answers using the tool.") .setTools(Collections.singletonList(aiSearchTool)); - agentsAsyncClient.createAgentVersion("ai-search-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java index 1ec6e97364840..3ee685afce2a8 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionAsync.java @@ -45,6 +45,7 @@ public class AzureFunctionAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "azure-function-agent"; String inputQueueName = Configuration.getGlobalConfiguration().get("STORAGE_INPUT_QUEUE_NAME"); String outputQueueName = Configuration.getGlobalConfiguration().get("STORAGE_OUTPUT_QUEUE_NAME"); String queueServiceEndpoint = Configuration.getGlobalConfiguration().get("STORAGE_QUEUE_SERVICE_ENDPOINT"); @@ -54,7 +55,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("azure-function-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -84,7 +85,7 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(azureFunctionTool)); - agentsAsyncClient.createAgentVersion("azure-function-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java index bd6193d39bb89..98184c9c3bcb9 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingCustomSearchAsync.java @@ -38,6 +38,7 @@ public class BingCustomSearchAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "bing-custom-search-agent"; String connectionId = Configuration.getGlobalConfiguration().get("BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID"); String instanceName = Configuration.getGlobalConfiguration().get("BING_CUSTOM_SEARCH_INSTANCE_NAME"); @@ -46,7 +47,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("bing-custom-search-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -61,7 +62,7 @@ public static void main(String[] args) { + "Use the available Bing Custom Search tools to answer questions and perform tasks.") .setTools(Collections.singletonList(bingCustomSearchTool)); - agentsAsyncClient.createAgentVersion("bing-custom-search-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java index af4cebe02bfd4..e0311fe8da886 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BingGroundingAsync.java @@ -36,6 +36,7 @@ public class BingGroundingAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "bing-grounding-agent"; String bingConnectionId = Configuration.getGlobalConfiguration().get("BING_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -43,7 +44,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("bing-grounding-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -58,7 +59,7 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant. Use Bing to find up-to-date information.") .setTools(Collections.singletonList(bingTool)); - agentsAsyncClient.createAgentVersion("bing-grounding-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java index fa930daf76825..3ccfb218633e5 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/BrowserAutomationAsync.java @@ -35,6 +35,7 @@ public class BrowserAutomationAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "browser-agent"; String connectionId = Configuration.getGlobalConfiguration().get("BROWSER_AUTOMATION_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -42,7 +43,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("browser-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -57,7 +58,7 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can interact with web pages.") .setTools(Collections.singletonList(browserTool)); - agentsAsyncClient.createAgentVersion("browser-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java index 959720fdab16e..e6a8e75167617 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CodeInterpreterAsync.java @@ -36,13 +36,14 @@ public class CodeInterpreterAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "code-interpreter-agent"; AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("code-interpreter-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -54,7 +55,7 @@ public static void main(String[] args) { + "When asked to perform calculations or data analysis, use the code interpreter to run Python code.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("code-interpreter-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java index 415f56de9b85a..c8ffda08fa5b3 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseAsync.java @@ -5,8 +5,8 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.AgentsServiceVersion; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ComputerEnvironment; import com.azure.ai.agents.models.ComputerUsePreviewTool; @@ -64,6 +64,7 @@ public static void main(String[] args) { Configuration configuration = Configuration.getGlobalConfiguration(); String endpoint = configuration.get("FOUNDRY_PROJECT_ENDPOINT"); String model = configuration.get("AZURE_COMPUTER_USE_MODEL_DEPLOYMENT_NAME", "computer-use-preview"); + String agentName = "ComputerUseAgent"; AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) @@ -71,7 +72,7 @@ public static void main(String[] args) { .serviceVersion(AgentsServiceVersion.getLatest()); AgentsAsyncClient agentsClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("ComputerUseAgent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); // Load screenshot assets Map screenshots; @@ -123,7 +124,7 @@ public static void main(String[] args) { ); // Create agent and run the interaction loop - agentsClient.createAgentVersion("ComputerUseAgent", agentDefinition) + agentsClient.createAgentVersion(agentName, agentDefinition) .doOnNext(agent -> { agentRef.set(agent); System.out.printf("Agent created (id: %s, name: %s, version: %s)%n", diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java index d2f9f82f8b1a3..9a8e426f8c79e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ComputerUseSync.java @@ -5,8 +5,8 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.AgentsServiceVersion; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.ComputerEnvironment; import com.azure.ai.agents.models.ComputerUsePreviewTool; diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java index d41e340aa8838..07843dfde2efa 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/CustomCodeInterpreterAsync.java @@ -35,6 +35,7 @@ public class CustomCodeInterpreterAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "CustomCodeInterpreterAgent"; String mcpServerUrl = Configuration.getGlobalConfiguration().get("MCP_SERVER_URL"); String connectionId = Configuration.getGlobalConfiguration().get("MCP_PROJECT_CONNECTION_ID"); @@ -43,7 +44,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("CustomCodeInterpreterAgent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -56,7 +57,7 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can run Python code to analyze data and solve problems.") .setTools(Collections.singletonList(customCodeInterpreter)); - agentsAsyncClient.createAgentVersion("CustomCodeInterpreterAgent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java index 7c9ac4206938c..bd87b31b5e3a1 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FabricAsync.java @@ -36,6 +36,7 @@ public class FabricAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "fabric-agent"; String fabricConnectionId = Configuration.getGlobalConfiguration().get("FABRIC_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -43,7 +44,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("fabric-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -59,7 +60,7 @@ public static void main(String[] args) { .setInstructions("You are a data assistant that can query Microsoft Fabric data.") .setTools(Collections.singletonList(fabricTool)); - agentsAsyncClient.createAgentVersion("fabric-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java index 0ac062513660c..5c83166ccc42c 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FunctionCallAsync.java @@ -41,13 +41,14 @@ public class FunctionCallAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "function-call-agent"; AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("function-call-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -80,7 +81,7 @@ public static void main(String[] args) { + "When asked about the weather, use the get_weather function to retrieve weather data.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("function-call-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java index 964db2c90f72c..97db6514e0bca 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/ImageGenerationAsync.java @@ -36,6 +36,7 @@ public class ImageGenerationAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "image-gen-agent"; String imageModel = Configuration.getGlobalConfiguration().get("IMAGE_GENERATION_MODEL_DEPLOYMENT_NAME"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -43,7 +44,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("image-gen-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -57,7 +58,7 @@ public static void main(String[] args) { .setInstructions("You are a creative assistant that can generate images based on descriptions.") .setTools(Collections.singletonList(imageGenTool)); - agentsAsyncClient.createAgentVersion("image-gen-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java index 24656e4886278..3634d9dfa914e 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpAsync.java @@ -41,13 +41,14 @@ public class McpAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "mcp-agent"; AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("mcp-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -62,7 +63,7 @@ public static void main(String[] args) { + "Use the available MCP tools to answer questions and perform tasks.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("mcp-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java index 7d2da3867bfd8..159fcdc579bc7 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/McpWithConnectionAsync.java @@ -38,6 +38,7 @@ public class McpWithConnectionAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "mcp-connection-agent"; String mcpConnectionId = Configuration.getGlobalConfiguration().get("MCP_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -45,7 +46,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("mcp-connection-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -58,7 +59,7 @@ public static void main(String[] args) { .setInstructions("Use MCP tools as needed") .setTools(Collections.singletonList(mcpTool)); - agentsAsyncClient.createAgentVersion("mcp-connection-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java index bd788045d46e0..3128a063aac89 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java @@ -44,6 +44,7 @@ public class MemorySearchAsync { public static void main(String[] args) throws Exception { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "memory-search-agent"; String chatModel = Configuration.getGlobalConfiguration().get("AZURE_AI_CHAT_MODEL_DEPLOYMENT_NAME"); String embeddingModel = Configuration.getGlobalConfiguration().get("AZURE_AI_EMBEDDING_MODEL_DEPLOYMENT_NAME"); @@ -52,7 +53,7 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("memory-search-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); ConversationServiceAsync conversationServiceAsync = builder.buildOpenAIAsyncClient().conversations(); // Memory store operations use sync client for setup/teardown BetaMemoryStoresClient memoryStoresClient = builder.beta().buildBetaMemoryStoresClient(); @@ -84,7 +85,7 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant that answers general questions.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("memory-search-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java index b755d6e48cb92..e36c1aada8e46 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiAsync.java @@ -37,13 +37,14 @@ public class OpenApiAsync { public static void main(String[] args) throws Exception { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "openapi-agent"; AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("openapi-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -59,7 +60,7 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant. Use the OpenAPI tool when asked to call an API.") .setTools(Collections.singletonList(openApiTool)); - agentsAsyncClient.createAgentVersion("openapi-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java index 9fc2d8ad1f17d..156d62e252e5d 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSample.java @@ -82,11 +82,10 @@ public static void main(String[] args) throws Exception { SampleUtils.pinAgentVersion(agentsClient, agentVersion); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentVersion.getName()); - ResponseCreateParams.Builder options = ResponseCreateParams.builder() - .maxOutputTokens(300L); - Response response = openAIClient.responses().create( - options.conversation(conversation.id()) + ResponseCreateParams.builder() + .maxOutputTokens(300L) + .conversation(conversation.id()) .build()); String text = response.output().stream() diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java index 67100967c0668..bd5bf30cd3be4 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiSync.java @@ -85,11 +85,10 @@ public static void main(String[] args) throws Exception { SampleUtils.pinAgentVersion(agentsClient, agentVersion); OpenAIClient openAIClient = builder.buildAgentScopedOpenAIClient(agentVersion.getName()); - ResponseCreateParams.Builder options = ResponseCreateParams.builder() - .maxOutputTokens(300L); - Response response = openAIClient.responses().create( - options.conversation(conversation.id()) + ResponseCreateParams.builder() + .maxOutputTokens(300L) + .conversation(conversation.id()) .build()); String text = response.output().stream() diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java index c2e2df23733b1..4a0159d138265 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/OpenApiWithConnectionAsync.java @@ -39,6 +39,7 @@ public class OpenApiWithConnectionAsync { public static void main(String[] args) throws Exception { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "openapi-connection-agent"; String connectionId = Configuration.getGlobalConfiguration().get("OPENAPI_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -46,7 +47,7 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("openapi-connection-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -65,7 +66,7 @@ public static void main(String[] args) throws Exception { .setInstructions("You are a helpful assistant.") .setTools(Collections.singletonList(openApiTool)); - agentsAsyncClient.createAgentVersion("openapi-connection-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java index 24a96cadcd7a6..bccd1ee1940ef 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/SharePointGroundingAsync.java @@ -36,6 +36,7 @@ public class SharePointGroundingAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "sharepoint-agent"; String sharepointConnectionId = Configuration.getGlobalConfiguration().get("SHAREPOINT_PROJECT_CONNECTION_ID"); AgentsClientBuilder builder = new AgentsClientBuilder() @@ -43,7 +44,7 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("sharepoint-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -59,7 +60,7 @@ public static void main(String[] args) { .setInstructions("You are a helpful assistant that can search through SharePoint documents.") .setTools(Collections.singletonList(sharepointTool)); - agentsAsyncClient.createAgentVersion("sharepoint-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java index bf02bbbc7c28a..80bd5611e9dc3 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WebSearchAsync.java @@ -35,13 +35,14 @@ public class WebSearchAsync { public static void main(String[] args) { String endpoint = Configuration.getGlobalConfiguration().get("FOUNDRY_PROJECT_ENDPOINT"); String model = Configuration.getGlobalConfiguration().get("FOUNDRY_MODEL_NAME"); + String agentName = "web-search-agent"; AgentsClientBuilder builder = new AgentsClientBuilder() .credential(new DefaultAzureCredentialBuilder().build()) .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient("web-search-agent"); + OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); AtomicReference agentRef = new AtomicReference<>(); @@ -53,7 +54,7 @@ public static void main(String[] args) { + "When asked to find information, use the web search tool to gather relevant data.") .setTools(Collections.singletonList(tool)); - agentsAsyncClient.createAgentVersion("web-search-agent", agentDefinition) + agentsAsyncClient.createAgentVersion(agentName, agentDefinition) .flatMap(agent -> { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); From 3adba743cb431e363352dde4193989336cdb39f3 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 15:00:46 -0700 Subject: [PATCH 08/17] migrate filesearch --- .../ai/agents/tools/FileSearchAsync.java | 29 +++++++++---------- .../azure/ai/agents/tools/FileSearchSync.java | 27 ++++++++--------- 2 files changed, 26 insertions(+), 30 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchAsync.java index 3e5d423c229be..94aa6306e7d43 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchAsync.java @@ -5,9 +5,7 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FileSearchTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -15,6 +13,7 @@ import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClient; +import com.openai.client.OpenAIClientAsync; import com.openai.models.files.FileCreateParams; import com.openai.models.files.FileObject; import com.openai.models.files.FilePurpose; @@ -58,10 +57,9 @@ public static void main(String[] args) throws Exception { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); ConversationServiceAsync conversationServiceAsync = builder.buildOpenAIAsyncClient().conversations(); // Vector store and file operations use the sync OpenAI client for setup - OpenAIClient openAIClient = builder.buildOpenAIClient(); + OpenAIClient projectOpenAIClient = builder.buildOpenAIClient(); AtomicReference agentRef = new AtomicReference<>(); AtomicReference conversationIdRef = new AtomicReference<>(); @@ -75,13 +73,13 @@ public static void main(String[] args) throws Exception { Path tempFile = Files.createTempFile("sample_document", ".txt"); Files.write(tempFile, sampleContent.getBytes(StandardCharsets.UTF_8)); - FileObject uploadedFile = openAIClient.files().create(FileCreateParams.builder() + FileObject uploadedFile = projectOpenAIClient.files().create(FileCreateParams.builder() .file(tempFile) .purpose(FilePurpose.ASSISTANTS) .build()); System.out.println("Uploaded file: " + uploadedFile.id()); - VectorStore vectorStore = openAIClient.vectorStores().create(VectorStoreCreateParams.builder() + VectorStore vectorStore = projectOpenAIClient.vectorStores().create(VectorStoreCreateParams.builder() .name("SampleVectorStore") .fileIds(Collections.singletonList(uploadedFile.id())) .build()); @@ -100,19 +98,20 @@ public static void main(String[] args) throws Exception { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClientAsync agentOpenAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agent.getName()); - return Mono.fromFuture(conversationServiceAsync.create()) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) + .then(Mono.fromFuture(conversationServiceAsync.create())) .flatMap(conversation -> { conversationIdRef.set(conversation.id()); System.out.println("Created conversation: " + conversation.id()); - return responsesAsyncClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + return Mono.fromFuture(() -> agentOpenAIAsyncClient.responses().create( ResponseCreateParams.builder() .conversation(conversation.id()) - .input("What is the largest planet in the Solar System?")); + .input("What is the largest planet in the Solar System?") + .build())); }); }) .doOnNext(response -> { @@ -159,8 +158,8 @@ public static void main(String[] args) throws Exception { return Mono.empty(); })) .doFinally(signal -> { - openAIClient.vectorStores().delete(vectorStore.id()); - openAIClient.files().delete(uploadedFile.id()); + projectOpenAIClient.vectorStores().delete(vectorStore.id()); + projectOpenAIClient.files().delete(uploadedFile.id()); try { Files.deleteIfExists(tempFile); } catch (Exception ignored) { diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchSync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchSync.java index 0bd3024556512..f029249bfb1b9 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchSync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/FileSearchSync.java @@ -5,9 +5,7 @@ import com.azure.ai.agents.AgentsClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FileSearchTool; import com.azure.ai.agents.models.PromptAgentDefinition; @@ -56,9 +54,8 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsClient agentsClient = builder.buildAgentsClient(); - ResponsesClient responsesClient = builder.buildResponsesClient(); - ConversationService conversationService = builder.buildOpenAIClient().conversations(); - OpenAIClient openAIClient = builder.buildOpenAIClient(); + OpenAIClient projectOpenAIClient = builder.buildOpenAIClient(); + ConversationService conversationService = projectOpenAIClient.conversations(); AgentVersionDetails agent = null; Conversation conversation = null; @@ -76,14 +73,14 @@ public static void main(String[] args) { tempFile = Files.createTempFile("sample_document", ".txt"); Files.write(tempFile, sampleContent.getBytes(StandardCharsets.UTF_8)); - uploadedFile = openAIClient.files().create(FileCreateParams.builder() + uploadedFile = projectOpenAIClient.files().create(FileCreateParams.builder() .file(tempFile) .purpose(FilePurpose.ASSISTANTS) .build()); System.out.println("Uploaded file: " + uploadedFile.id()); // Create a vector store with the uploaded file - vectorStore = openAIClient.vectorStores().create(VectorStoreCreateParams.builder() + vectorStore = projectOpenAIClient.vectorStores().create(VectorStoreCreateParams.builder() .name("SampleVectorStore") .fileIds(Collections.singletonList(uploadedFile.id())) .build()); @@ -105,18 +102,18 @@ public static void main(String[] args) { agent = agentsClient.createAgentVersion("file-search-agent", agentDefinition); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + SampleUtils.pinAgentVersion(agentsClient, agent); + OpenAIClient agentOpenAIClient = builder.buildAgentScopedOpenAIClient(agent.getName()); // Create a conversation and ask the agent conversation = conversationService.create(); System.out.println("Created conversation: " + conversation.id()); - Response response = responsesClient.createAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), + Response response = agentOpenAIClient.responses().create( ResponseCreateParams.builder() .conversation(conversation.id()) - .input("What is the largest planet in the Solar System?")); + .input("What is the largest planet in the Solar System?") + .build()); // Process and display the response for (ResponseOutputItem outputItem : response.output()) { @@ -164,11 +161,11 @@ public static void main(String[] args) { System.out.println("Agent deleted"); } if (vectorStore != null) { - openAIClient.vectorStores().delete(vectorStore.id()); + projectOpenAIClient.vectorStores().delete(vectorStore.id()); System.out.println("Vector store deleted"); } if (uploadedFile != null) { - openAIClient.files().delete(uploadedFile.id()); + projectOpenAIClient.files().delete(uploadedFile.id()); System.out.println("File deleted"); } } From 118063db3f8b2189c74a7fd6fb913fd91db019c8 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 15:03:19 -0700 Subject: [PATCH 09/17] typo --- .../com/azure/ai/agents/CreateResponseWithConversation.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java index 87e5dad4dc630..6f1e967a81e95 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java @@ -24,8 +24,8 @@ import java.util.Collections; /** - * This sample demonstrates how to to create a response with a conversation - * against an agent. + * This sample demonstrates how to invoke the OpenAI Responses API against a Prompt Agent, + * routing all traffic through the agent's endpoint URL. */ public class CreateResponseWithConversation { public static void main(String[] args) { From f3ba891221112f786150d88036169daf835653cf Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 8 Sep 2026 15:28:22 -0700 Subject: [PATCH 10/17] update readme --- sdk/ai/azure-ai-agents/README.md | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index 193b967e8277b..2ac7548a538f6 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -65,7 +65,7 @@ AgentsAsyncClient agentsAsyncClient = new AgentsClientBuilder() The Agents client library has the following sub-clients which group the different operations that can be performed: - `AgentsClient` / `AgentsAsyncClient`: Perform operations related to agents, such as creating, retrieving, updating, and deleting agents. When `allowPreview(true)` is configured, these clients can also use preview draft versions, hosted-agent sessions, session files, and code package operations. - `BetaAgentsClient` / `BetaAgentsAsyncClient` **(preview)**: Perform preview agent optimization operations. -- `ResponsesClient` / `ResponsesAsyncClient`: Handle responses operations. See the [OpenAI's Responses API documentation][openai_responses_api_docs] for more information. +- `ResponsesClient` / `ResponsesAsyncClient`: Create responses that require Azure-specific request fields, such as an explicit `AgentReference` or structured inputs. For standard OpenAI Responses API calls through a configured agent endpoint, use an agent-scoped OpenAI client. See the [OpenAI Responses API documentation][openai_responses_api_docs] for more information. - `BetaMemoryStoresClient` / `BetaMemoryStoresAsyncClient` **(preview)**: Manage memory stores and individual memory items for agents. - `ToolboxesClient` / `ToolboxesAsyncClient`: Manage toolboxes and toolbox versions. @@ -102,7 +102,11 @@ The [OpenAI Official Java SDK][openai_java_sdk] is imported transitively and can OpenAIClient openAIClient = builder.buildOpenAIClient(); OpenAIClientAsync openAIAsyncClient = builder.buildOpenAIAsyncClient(); -// OpenAI SDK ResponseService accessed from ResponsesClient +// Agent-scoped OpenAI clients for invoking a configured agent endpoint. +OpenAIClient agentScopedOpenAIClient = builder.buildAgentScopedOpenAIClient(agentName); +OpenAIClientAsync agentScopedOpenAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agentName); + +// ResponsesClient wraps the OpenAI SDK's ResponseService with Azure-specific options. ResponsesClient responsesClient = builder.buildResponsesClient(); ResponseService responseService = responsesClient.getResponseService(); @@ -221,13 +225,13 @@ ResponseCreateParams responseRequest = new ResponseCreateParams.Builder() Response result = client.responses().create(responseRequest); ``` -Remember to adjust your base URL so that your AI Foundry project `endpoint`'s path ends with `openai/v1` like it's shown in the above code snippet. +For this direct setup, ensure that the AI Foundry project `endpoint` path ends with `openai/v1`, as shown above. ## Examples ### Prompt Agent -This example will show how to create the context necessary for a `PromptAgent` to work. Note that the way that context is handled in this scenario would allow you to share the context with multiple agents. +This example shows how to create and invoke a `PromptAgent` with conversation context that can be shared across multiple agents. #### Create an Agent @@ -238,7 +242,7 @@ PromptAgentDefinition promptAgentDefinition = new PromptAgentDefinition("gpt-4o" AgentVersionDetails agent = agentsClient.createAgentVersion("my-agent", promptAgentDefinition); ``` -This will return an `AgentVersionDetails` which contains the information necessary to create an `AgentReference`. But first it's necessary to setup the `Conversation` and its messages to be able to obtain `Response`s with a centralized context. +This returns an `AgentVersionDetails` containing the name and version used to configure the agent endpoint. The following steps also create a `Conversation` to provide centralized context that can be shared across agents. #### Create conversation @@ -248,7 +252,7 @@ First we need to create our `Conversation` object so we can attach items to it: Conversation conversation = conversationsClient.create(); ``` -With `conversation.id()` contains the reference we will use to append messages to this `Conversation`. `Conversation` objects can be used by multiple agents and serve the purpose of being a centralized source of context. To add items: +The value returned by `conversation.id()` identifies the conversation when appending messages. `Conversation` objects can be used by multiple agents as a centralized source of context. To add items: ```java com.azure.ai.agents.add_message_to_conversation conversationsClient.items().create( @@ -270,7 +274,7 @@ To scope conversation operations to a delegated end user, set `FOUNDRY_USER_IDEN #### Configure the agent endpoint -Before invoking the agent, point its endpoint at the version you just created and enable the OpenAI Responses protocol on it: +An agent can have multiple versions. Before invoking it through the OpenAI Responses API, configure its endpoint with a version-selection rule and enable the Responses protocol. This example sends all endpoint traffic to the version just created; the endpoint configuration remains in effect until it is updated again: ```java com.azure.ai.agents.configure_agent_endpoint AgentEndpointConfig endpointConfig = new AgentEndpointConfig() @@ -284,7 +288,7 @@ agentsClient.updateAgentDetails(agent.getName(), #### Text generation with Responses -With the agent endpoint configured, invoke the OpenAI Responses API through an agent-scoped OpenAI client: +With the agent endpoint configured, build an agent-scoped OpenAI client and invoke the OpenAI Responses API: ```java com.azure.ai.agents.create_response OpenAIClient agentScopedClient = builder.buildAgentScopedOpenAIClient(agent.getName()); @@ -294,6 +298,8 @@ Response response = agentScopedClient.responses().create(ResponseCreateParams.bu .build()); ``` +For asynchronous calls, use `buildAgentScopedOpenAIAsyncClient`. + ### Using Agent tools Agents can be enhanced with specialized tools for various capabilities. For complete working examples, see the `tools/` folder under [samples](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools). @@ -462,7 +468,7 @@ AzureFunctionTool azureFunctionTool = new AzureFunctionTool( ); ``` -*After calling `responsesClient.createAzureResponse()`, the agent enqueues function arguments to the input queue. Your Azure Function processes the request and returns results via the output queue.* +*When the agent handles a response, it enqueues function arguments to the input queue. Your Azure Function processes the request and returns results through the output queue.* See the full sample in [AzureFunctionSync.java](https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/AzureFunctionSync.java). @@ -770,11 +776,11 @@ See the full end-to-end sample in [ShellToolboxSample.java](https://github.com/A ### Streaming responses -The `ResponsesClient` and `ResponsesAsyncClient` support streaming, which allows you to process response events as they arrive rather than waiting for the full response. This is useful for displaying text to users in real time and observing tool execution progress. +An agent-scoped OpenAI client can stream response events as they arrive instead of waiting for the complete response. This is useful for displaying text in real time and observing tool execution progress. #### Synchronous streaming -The synchronous streaming methods return `IterableStream`, which can be consumed with a standard for-each loop. Use the `ResponseAccumulator` from the OpenAI SDK to collect events into a final `Response`: +The OpenAI SDK's synchronous `createStreaming` method returns a `StreamResponse`. Close it with try-with-resources, and use `ResponseAccumulator` to collect the events into a final `Response`: ```java com.azure.ai.agents.streaming.simple_sync // Use ResponseAccumulator to collect streamed events into a final Response @@ -803,7 +809,7 @@ See the full samples in [SimpleStreamingSync.java](https://github.com/Azure/azur #### Asynchronous streaming -The asynchronous streaming methods return `Flux`, integrating naturally with Reactor pipelines: +The OpenAI SDK's asynchronous `createStreaming` method returns an `AsyncStreamResponse`. Subscribe to its event callbacks and use `onCompleteFuture()` to track terminal completion: ```java com.azure.ai.agents.streaming.simple_async // OpenAI streaming events arrive through callbacks. This Mono only tracks terminal completion. From 60154a46986c47c71d4198c5043a25899c32ce2e Mon Sep 17 00:00:00 2001 From: kaylieee Date: Tue, 15 Sep 2026 23:58:52 -0700 Subject: [PATCH 11/17] add util for streaming responses --- sdk/ai/azure-ai-agents/CHANGELOG.md | 2 ++ .../azure/ai/agents/ResponsesAsyncClient.java | 4 +-- .../com/azure/ai/agents/ResponsesClient.java | 4 +-- .../StreamingResponseUtils.java} | 8 ++--- .../azure/ai/agents/util/package-info.java | 7 ++++ .../StreamingResponseUtilsTest.java} | 36 +++++++++---------- 6 files changed, 35 insertions(+), 26 deletions(-) rename sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/{implementation/StreamingUtils.java => util/StreamingResponseUtils.java} (96%) create mode 100644 sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/package-info.java rename sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/{implementation/StreamingUtilsTest.java => util/StreamingResponseUtilsTest.java} (88%) diff --git a/sdk/ai/azure-ai-agents/CHANGELOG.md b/sdk/ai/azure-ai-agents/CHANGELOG.md index d471baf8fa858..24864e66b7973 100644 --- a/sdk/ai/azure-ai-agents/CHANGELOG.md +++ b/sdk/ai/azure-ai-agents/CHANGELOG.md @@ -4,6 +4,8 @@ ### Features Added +- Added public `StreamingResponseUtils` in the `com.azure.ai.agents.util` package for converting OpenAI streaming + responses to Azure SDK `IterableStream` and Reactor `Flux` types. - Added `BetaAgentTelephonyClient` and `BetaAgentTelephonyAsyncClient`, built through `AgentsClientBuilder.beta()`, for managing voice-agent outbound call jobs and telephony campaigns. - Added `BetaAgentEndpointConversationsClient` and `BetaAgentEndpointConversationsAsyncClient`, built through diff --git a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesAsyncClient.java b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesAsyncClient.java index 07f98c4a6d648..16ada87bfcb37 100644 --- a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesAsyncClient.java +++ b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesAsyncClient.java @@ -5,8 +5,8 @@ package com.azure.ai.agents; import com.azure.ai.agents.implementation.OpenAIJsonHelper; -import com.azure.ai.agents.implementation.StreamingUtils; import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.util.StreamingResponseUtils; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; @@ -86,7 +86,7 @@ public Flux createStreamingAzureResponse(AzureCreateRespons Map additionalBodyProperties = OpenAIJsonHelper.toJsonValueMap(createResponse); params.additionalBodyProperties(additionalBodyProperties); - return StreamingUtils.toFlux(this.responseServiceAsync.createStreaming(params.build())); + return StreamingResponseUtils.toFlux(this.responseServiceAsync.createStreaming(params.build())); } /** diff --git a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesClient.java b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesClient.java index f179f0192fe22..834772db0f0ad 100644 --- a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesClient.java +++ b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/ResponsesClient.java @@ -5,9 +5,9 @@ package com.azure.ai.agents; import com.azure.ai.agents.implementation.OpenAIJsonHelper; -import com.azure.ai.agents.implementation.StreamingUtils; import com.azure.ai.agents.models.AzureCreateResponseDetails; import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.util.StreamingResponseUtils; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.ReturnType; @@ -86,7 +86,7 @@ public IterableStream createStreamingAzureResponse(AzureCre Map additionalBodyProperties = OpenAIJsonHelper.toJsonValueMap(createResponse); params.additionalBodyProperties(additionalBodyProperties); - return StreamingUtils.toIterableStream(this.responseService.createStreaming(params.build())); + return StreamingResponseUtils.toIterableStream(this.responseService.createStreaming(params.build())); } /** diff --git a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/implementation/StreamingUtils.java b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/StreamingResponseUtils.java similarity index 96% rename from sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/implementation/StreamingUtils.java rename to sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/StreamingResponseUtils.java index 83e7b28d7d7d6..6d03cf242011e 100644 --- a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/implementation/StreamingUtils.java +++ b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/StreamingResponseUtils.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.ai.agents.implementation; +package com.azure.ai.agents.util; import com.azure.core.util.IterableStream; import com.azure.core.util.logging.ClientLogger; @@ -17,11 +17,11 @@ /** * Utility methods for bridging OpenAI streaming types to Azure SDK / Reactor types. */ -public final class StreamingUtils { +public final class StreamingResponseUtils { - private static final ClientLogger LOGGER = new ClientLogger(StreamingUtils.class); + private static final ClientLogger LOGGER = new ClientLogger(StreamingResponseUtils.class); - private StreamingUtils() { + private StreamingResponseUtils() { } /** diff --git a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/package-info.java b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/package-info.java new file mode 100644 index 0000000000000..f6db93143c394 --- /dev/null +++ b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/util/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing utility classes for Azure AI Agents. + */ +package com.azure.ai.agents.util; diff --git a/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/implementation/StreamingUtilsTest.java b/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/util/StreamingResponseUtilsTest.java similarity index 88% rename from sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/implementation/StreamingUtilsTest.java rename to sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/util/StreamingResponseUtilsTest.java index 8af0eb8c4d6b8..d85373d5c3598 100644 --- a/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/implementation/StreamingUtilsTest.java +++ b/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/util/StreamingResponseUtilsTest.java @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -package com.azure.ai.agents.implementation; +package com.azure.ai.agents.util; import com.azure.core.util.IterableStream; import com.openai.core.http.AsyncStreamResponse; @@ -27,9 +27,9 @@ import static org.junit.jupiter.api.Assertions.assertTrue; /** - * Unit tests for {@link StreamingUtils}. + * Unit tests for {@link StreamingResponseUtils}. */ -public class StreamingUtilsTest { +public class StreamingResponseUtilsTest { // ======================================================================== // toIterableStream tests @@ -40,7 +40,7 @@ public void toIterableStreamSingleItem() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.of("hello"), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); List items = collect(result); assertEquals(1, items.size()); @@ -53,7 +53,7 @@ public void toIterableStreamMultipleItems() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.of("event1", "event2", "event3"), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); List items = collect(result); assertEquals(3, items.size()); @@ -68,7 +68,7 @@ public void toIterableStreamEmptyClosesResource() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.empty(), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); List items = collect(result); assertTrue(items.isEmpty()); @@ -84,7 +84,7 @@ public void toIterableStreamPreservesOrder() { } StreamResponse streamResponse = testStreamResponse(expected.stream(), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); List items = collect(result); assertEquals(expected, items); @@ -96,7 +96,7 @@ public void toIterableStreamNotClosedBeforeFullConsumption() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.of("a", "b", "c"), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); Iterator iterator = result.iterator(); // Consume only one item @@ -116,7 +116,7 @@ public void toIterableStreamIteratorThrowsWhenExhausted() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.of("only"), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); Iterator iterator = result.iterator(); assertEquals("only", iterator.next()); @@ -129,7 +129,7 @@ public void toIterableStreamThrowsOnSecondIteratorCall() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.of("a", "b"), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); // First iterator() call should succeed Iterator first = result.iterator(); @@ -144,7 +144,7 @@ public void toIterableStreamSecondIteratorCallAfterFullConsumptionThrows() { AtomicBoolean closed = new AtomicBoolean(false); StreamResponse streamResponse = testStreamResponse(Stream.of("a", "b"), closed); - IterableStream result = StreamingUtils.toIterableStream(streamResponse); + IterableStream result = StreamingResponseUtils.toIterableStream(streamResponse); // Fully consume the first iterator List items = collect(result); @@ -164,7 +164,7 @@ public void toIterableStreamSecondIteratorCallAfterFullConsumptionThrows() { public void toFluxSingleItem() { TestAsyncStreamResponse asyncStream = new TestAsyncStreamResponse<>(); - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); StepVerifier.create(flux).then(() -> { asyncStream.emit("hello"); @@ -176,7 +176,7 @@ public void toFluxSingleItem() { public void toFluxMultipleItems() { TestAsyncStreamResponse asyncStream = new TestAsyncStreamResponse<>(); - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); StepVerifier.create(flux).then(() -> { asyncStream.emit("event1"); @@ -190,7 +190,7 @@ public void toFluxMultipleItems() { public void toFluxEmptyStream() { TestAsyncStreamResponse asyncStream = new TestAsyncStreamResponse<>(); - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); StepVerifier.create(flux).then(asyncStream::complete).verifyComplete(); } @@ -200,7 +200,7 @@ public void toFluxPropagatesError() { TestAsyncStreamResponse asyncStream = new TestAsyncStreamResponse<>(); RuntimeException expectedError = new RuntimeException("stream failed"); - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); StepVerifier.create(flux).then(() -> { asyncStream.emit("before-error"); @@ -216,7 +216,7 @@ public void toFluxErrorWithNoEmissions() { TestAsyncStreamResponse asyncStream = new TestAsyncStreamResponse<>(); RuntimeException expectedError = new RuntimeException("immediate failure"); - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); StepVerifier.create(flux) .then(() -> asyncStream.completeWithError(expectedError)) @@ -232,7 +232,7 @@ public void toFluxPreservesOrder() { expected.add("item-" + i); } - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); StepVerifier.create(flux).then(() -> { for (String item : expected) { @@ -250,7 +250,7 @@ public void toFluxPreservesOrder() { public void toFluxClosesOnDispose() { TestAsyncStreamResponse asyncStream = new TestAsyncStreamResponse<>(); - Flux flux = StreamingUtils.toFlux(asyncStream); + Flux flux = StreamingResponseUtils.toFlux(asyncStream); // Subscribe and immediately dispose flux.subscribe().dispose(); From 55cdb67d388504861bed118d3b98356dc65a00fc Mon Sep 17 00:00:00 2001 From: kaylieee Date: Wed, 16 Sep 2026 00:10:35 -0700 Subject: [PATCH 12/17] update samples to use util --- sdk/ai/azure-ai-agents/README.md | 18 ++++++++--------- .../CodeInterpreterStreamingAsync.java | 20 +++++++++---------- .../streaming/FunctionCallStreamingAsync.java | 20 +++++++++---------- .../streaming/SimpleStreamingAsync.java | 16 +++++++-------- 4 files changed, 37 insertions(+), 37 deletions(-) diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index 2ac7548a538f6..2818711d94590 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -809,10 +809,11 @@ See the full samples in [SimpleStreamingSync.java](https://github.com/Azure/azur #### Asynchronous streaming -The OpenAI SDK's asynchronous `createStreaming` method returns an `AsyncStreamResponse`. Subscribe to its event callbacks and use `onCompleteFuture()` to track terminal completion: +The OpenAI SDK's asynchronous `createStreaming` method returns an `AsyncStreamResponse`. +Use `StreamingResponseUtils.toFlux` to adapt it to a Reactor `Flux` and manage the underlying stream lifecycle: ```java com.azure.ai.agents.streaming.simple_async -// OpenAI streaming events arrive through callbacks. This Mono only tracks terminal completion. +// Adapt OpenAI streaming events to a Reactor Flux. Mono streamingCompletion = Mono.defer(() -> { ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( @@ -820,19 +821,18 @@ Mono streamingCompletion = Mono.defer(() -> { .input("Tell me a short story about a brave explorer.") .build()); - stream.subscribe(event -> responseAccumulator.accumulate(event) - .outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta()))); - - return Mono.fromFuture(stream.onCompleteFuture()) + return StreamingResponseUtils.toFlux(stream) + .doOnNext(event -> responseAccumulator.accumulate(event) + .outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta()))) + .then() .doOnSuccess(unused -> { System.out.println(); // newline after streamed text // Access the complete accumulated response Response response = responseAccumulator.response(); System.out.println("\nResponse ID: " + response.id()); - }) - .doFinally(signal -> stream.close()); + }); }); ``` diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java index b1c5145a1c313..df2ab638d7222 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/CodeInterpreterStreamingAsync.java @@ -5,14 +5,14 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.CodeInterpreterTool; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.util.StreamingResponseUtils; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; @@ -42,7 +42,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); AtomicReference agentRef = new AtomicReference<>(); @@ -60,17 +59,18 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.code_interpreter_async // Stream response asynchronously with Code Interpreter ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - return responsesAsyncClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("Calculate the first 10 prime numbers using Python.")) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) + .flatMapMany(ignored -> StreamingResponseUtils.toFlux( + openAIAsyncClient.responses().createStreaming(ResponseCreateParams.builder() + .input("Calculate the first 10 prime numbers using Python.") + .build()))) .doOnNext(event -> { responseAccumulator.accumulate(event); // Print text deltas as they arrive diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java index c824adaca8e02..0e6987cc5ca40 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/FunctionCallStreamingAsync.java @@ -5,15 +5,15 @@ import com.azure.ai.agents.AgentsAsyncClient; import com.azure.ai.agents.AgentsClientBuilder; -import com.azure.ai.agents.ResponsesAsyncClient; -import com.azure.ai.agents.models.AgentReference; -import com.azure.ai.agents.models.AzureCreateResponseOptions; +import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.FunctionTool; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.util.StreamingResponseUtils; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; +import com.openai.client.OpenAIClientAsync; import com.openai.helpers.ResponseAccumulator; import com.openai.models.responses.Response; import com.openai.models.responses.ResponseCreateParams; @@ -48,7 +48,6 @@ public static void main(String[] args) { .endpoint(endpoint); AgentsAsyncClient agentsAsyncClient = builder.buildAgentsAsyncClient(); - ResponsesAsyncClient responsesAsyncClient = builder.buildResponsesAsyncClient(); AtomicReference agentRef = new AtomicReference<>(); @@ -85,17 +84,18 @@ public static void main(String[] args) { agentRef.set(agent); System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion()); - AgentReference agentReference = new AgentReference(agent.getName()) - .setVersion(agent.getVersion()); + OpenAIClientAsync openAIAsyncClient + = builder.buildAgentScopedOpenAIAsyncClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.function_call_async // Stream response asynchronously with function tool ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); - return responsesAsyncClient.createStreamingAzureResponse( - new AzureCreateResponseOptions().setAgentReference(agentReference), - ResponseCreateParams.builder() - .input("What's the weather like in Seattle?")) + return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) + .flatMapMany(ignored -> StreamingResponseUtils.toFlux( + openAIAsyncClient.responses().createStreaming(ResponseCreateParams.builder() + .input("What's the weather like in Seattle?") + .build()))) .doOnNext(event -> { responseAccumulator.accumulate(event); // Print text deltas as they arrive diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java index 2f8c8982308f9..b7500e3e86133 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/streaming/SimpleStreamingAsync.java @@ -8,6 +8,7 @@ import com.azure.ai.agents.SampleUtils; import com.azure.ai.agents.models.AgentVersionDetails; import com.azure.ai.agents.models.PromptAgentDefinition; +import com.azure.ai.agents.util.StreamingResponseUtils; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.openai.client.OpenAIClientAsync; @@ -55,7 +56,7 @@ public static void main(String[] args) { OpenAIClientAsync openAIAsyncClient = builder.buildAgentScopedOpenAIAsyncClient(agent.getName()); // BEGIN: com.azure.ai.agents.streaming.simple_async - // OpenAI streaming events arrive through callbacks. This Mono only tracks terminal completion. + // Adapt OpenAI streaming events to a Reactor Flux. Mono streamingCompletion = Mono.defer(() -> { ResponseAccumulator responseAccumulator = ResponseAccumulator.create(); AsyncStreamResponse stream = openAIAsyncClient.responses().createStreaming( @@ -63,19 +64,18 @@ public static void main(String[] args) { .input("Tell me a short story about a brave explorer.") .build()); - stream.subscribe(event -> responseAccumulator.accumulate(event) - .outputTextDelta() - .ifPresent(textEvent -> System.out.print(textEvent.delta()))); - - return Mono.fromFuture(stream.onCompleteFuture()) + return StreamingResponseUtils.toFlux(stream) + .doOnNext(event -> responseAccumulator.accumulate(event) + .outputTextDelta() + .ifPresent(textEvent -> System.out.print(textEvent.delta()))) + .then() .doOnSuccess(unused -> { System.out.println(); // newline after streamed text // Access the complete accumulated response Response response = responseAccumulator.response(); System.out.println("\nResponse ID: " + response.id()); - }) - .doFinally(signal -> stream.close()); + }); }); // END: com.azure.ai.agents.streaming.simple_async From 4f37d9b481d8cb256a8b587329b8ac13463add38 Mon Sep 17 00:00:00 2001 From: Kaylie <50653231+kaylieee@users.noreply.github.com> Date: Wed, 16 Sep 2026 00:23:40 -0700 Subject: [PATCH 13/17] Update comment to clarify API routing Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../com/azure/ai/agents/CreateResponseWithConversation.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java index 6f1e967a81e95..1a06da66adc93 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java @@ -25,7 +25,7 @@ /** * This sample demonstrates how to invoke the OpenAI Responses API against a Prompt Agent, - * routing all traffic through the agent's endpoint URL. + * routing the Responses API request through the agent's endpoint URL. */ public class CreateResponseWithConversation { public static void main(String[] args) { From 54e5dc08cf66c06c80b605ee83332fa6ed3c9c22 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Wed, 16 Sep 2026 00:27:31 -0700 Subject: [PATCH 14/17] add back responses helper to readme --- sdk/ai/azure-ai-agents/README.md | 2 ++ .../src/samples/java/com/azure/ai/agents/ReadmeSamples.java | 3 +++ 2 files changed, 5 insertions(+) diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index 2818711d94590..48118eb61225c 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -296,6 +296,8 @@ OpenAIClient agentScopedClient = builder.buildAgentScopedOpenAIClient(agent.getN Response response = agentScopedClient.responses().create(ResponseCreateParams.builder() .conversation(conversation.id()) .build()); +// To extract Azure-specific response details: +AzureCreateResponseDetails azureResults = ResponsesClient.getAzureFields(response); ``` For asynchronous calls, use `buildAgentScopedOpenAIAsyncClient`. diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java index 1e88887489367..c38c63d31a82f 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java @@ -6,6 +6,7 @@ import com.azure.ai.agents.models.AgentEndpointConfig; import com.azure.ai.agents.models.AgentVersionDetails; +import com.azure.ai.agents.models.AzureCreateResponseDetails; import com.azure.ai.agents.models.FixedRatioVersionSelectionRule; import com.azure.ai.agents.models.PromptAgentDefinition; import com.azure.ai.agents.models.ProtocolConfiguration; @@ -85,6 +86,8 @@ public void readmeSamples() { Response response = agentScopedClient.responses().create(ResponseCreateParams.builder() .conversation(conversation.id()) .build()); + // To extract Azure-specific response details: + AzureCreateResponseDetails azureResults = ResponsesClient.getAzureFields(response); // END: com.azure.ai.agents.create_response // BEGIN: com.azure.ai.agents.openai_official_library From 425698a7c6c47d983133aac9378b404031f7909a Mon Sep 17 00:00:00 2001 From: kaylieee Date: Wed, 16 Sep 2026 00:27:46 -0700 Subject: [PATCH 15/17] fix indentation --- .../java/com/azure/ai/agents/tools/MemorySearchAsync.java | 8 ++++---- .../java/com/azure/ai/agents/tools/WorkIQAsync.java | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java index 3128a063aac89..e7776acea0b68 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/MemorySearchAsync.java @@ -96,10 +96,10 @@ public static void main(String[] args) throws Exception { firstConvRef.set(conv.id()); return SampleUtils.pinAgentVersion(agentsAsyncClient, agent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( - ResponseCreateParams.builder() - .conversation(conv.id()) - .input("I prefer dark roast coffee") - .build()))); + ResponseCreateParams.builder() + .conversation(conv.id()) + .input("I prefer dark roast coffee") + .build()))); }); }) .doOnNext(response -> System.out.println("First response received")) diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java index ace5fe457f859..947ad3bc71807 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/tools/WorkIQAsync.java @@ -71,10 +71,10 @@ public static void main(String[] args) { return SampleUtils.pinAgentVersion(agentsAsyncClient, createdAgent) .then(Mono.fromFuture(() -> openAIAsyncClient.responses().create( - ResponseCreateParams.builder() - .toolChoice(ToolChoiceOptions.REQUIRED) - .input(userInput) - .build()))) + ResponseCreateParams.builder() + .toolChoice(ToolChoiceOptions.REQUIRED) + .input(userInput) + .build()))) .doOnNext(response -> { System.out.println("Response status: " + response.status().map(Object::toString).orElse("unknown")); From f8ed2e923029b4ff72132a2224655f5fbe6454c2 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Wed, 16 Sep 2026 00:33:21 -0700 Subject: [PATCH 16/17] add singleton version selection rule helper --- sdk/ai/azure-ai-agents/CHANGELOG.md | 1 + sdk/ai/azure-ai-agents/README.md | 4 ++-- .../ai/agents/models/VersionSelector.java | 14 ++++++++++++ .../CreateResponseWithConversation.java | 6 ++--- .../com/azure/ai/agents/ReadmeSamples.java | 6 ++--- .../java/com/azure/ai/agents/SampleUtils.java | 5 ++--- .../agents/models/VersionSelectorTests.java | 22 +++++++++++++++++++ 7 files changed, 45 insertions(+), 13 deletions(-) create mode 100644 sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/models/VersionSelectorTests.java diff --git a/sdk/ai/azure-ai-agents/CHANGELOG.md b/sdk/ai/azure-ai-agents/CHANGELOG.md index 24864e66b7973..c515215e30dd9 100644 --- a/sdk/ai/azure-ai-agents/CHANGELOG.md +++ b/sdk/ai/azure-ai-agents/CHANGELOG.md @@ -4,6 +4,7 @@ ### Features Added +- Added `VersionSelector.setVersionSelectionRule` as a convenience for configuring a single version selection rule. - Added public `StreamingResponseUtils` in the `com.azure.ai.agents.util` package for converting OpenAI streaming responses to Azure SDK `IterableStream` and Reactor `Flux` types. - Added `BetaAgentTelephonyClient` and `BetaAgentTelephonyAsyncClient`, built through diff --git a/sdk/ai/azure-ai-agents/README.md b/sdk/ai/azure-ai-agents/README.md index 48118eb61225c..3fbb328e55582 100644 --- a/sdk/ai/azure-ai-agents/README.md +++ b/sdk/ai/azure-ai-agents/README.md @@ -278,8 +278,8 @@ An agent can have multiple versions. Before invoking it through the OpenAI Respo ```java com.azure.ai.agents.configure_agent_endpoint AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setVersionSelector(new VersionSelector().setVersionSelectionRule( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion()))) .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); agentsClient.updateAgentDetails(agent.getName(), diff --git a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/models/VersionSelector.java b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/models/VersionSelector.java index 8d85e6e949401..53a3f1345effe 100644 --- a/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/models/VersionSelector.java +++ b/sdk/ai/azure-ai-agents/src/main/java/com/azure/ai/agents/models/VersionSelector.java @@ -11,6 +11,7 @@ import com.azure.json.JsonToken; import com.azure.json.JsonWriter; import java.io.IOException; +import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -88,6 +89,19 @@ public VersionSelector setVersionSelectionRules(List versi return this; } + /** + * Set a single version selection rule. + * + *

This is a convenience method equivalent to calling {@link #setVersionSelectionRules(List)} with a singleton + * list.

+ * + * @param versionSelectionRule the version selection rule to set. + * @return the VersionSelector object itself. + */ + public VersionSelector setVersionSelectionRule(VersionSelectionRule versionSelectionRule) { + return setVersionSelectionRules(Collections.singletonList(versionSelectionRule)); + } + /** * {@inheritDoc} */ diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java index 1a06da66adc93..0be3a0b445cc5 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/CreateResponseWithConversation.java @@ -21,8 +21,6 @@ import com.openai.models.responses.ResponseOutputMessage; import com.openai.services.blocking.ConversationService; -import java.util.Collections; - /** * This sample demonstrates how to invoke the OpenAI Responses API against a Prompt Agent, * routing the Responses API request through the agent's endpoint URL. @@ -52,8 +50,8 @@ public static void main(String[] args) { System.out.printf("Agent created (id: %s, version: %s)\n", agent.getId(), agent.getVersion()); AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setVersionSelector(new VersionSelector().setVersionSelectionRule( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion()))) .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); agentsClient.updateAgentDetails(agent.getName(), new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig)); diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java index c38c63d31a82f..40ee3dfdf99e2 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/ReadmeSamples.java @@ -27,8 +27,6 @@ import com.openai.models.responses.ResponseCreateParams; import com.openai.services.blocking.ConversationService; -import java.util.Collections; - public final class ReadmeSamples { public void readmeSamples() { String endpoint = "my-resource-url"; @@ -52,8 +50,8 @@ public void readmeSamples() { // BEGIN: com.azure.ai.agents.configure_agent_endpoint AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion())))) + .setVersionSelector(new VersionSelector().setVersionSelectionRule( + new FixedRatioVersionSelectionRule(100).setAgentVersion(agent.getVersion()))) .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); agentsClient.updateAgentDetails(agent.getName(), diff --git a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java index e36d3a485b4b2..8b8410e91b343 100644 --- a/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java +++ b/sdk/ai/azure-ai-agents/src/samples/java/com/azure/ai/agents/SampleUtils.java @@ -18,7 +18,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Collections; public class SampleUtils { @@ -75,8 +74,8 @@ public static Path getResourcePath(String fileName) { private static UpdateAgentDetailsOptions createPinnedEndpointOptions(AgentVersionDetails versionDetails) { AgentEndpointConfig endpointConfig = new AgentEndpointConfig() - .setVersionSelector(new VersionSelector().setVersionSelectionRules(Collections.singletonList( - new FixedRatioVersionSelectionRule(100).setAgentVersion(versionDetails.getVersion())))) + .setVersionSelector(new VersionSelector().setVersionSelectionRule( + new FixedRatioVersionSelectionRule(100).setAgentVersion(versionDetails.getVersion()))) .setProtocolConfiguration(new ProtocolConfiguration().setResponses(new ResponsesProtocolConfiguration())); return new UpdateAgentDetailsOptions().setAgentEndpoint(endpointConfig); diff --git a/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/models/VersionSelectorTests.java b/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/models/VersionSelectorTests.java new file mode 100644 index 0000000000000..1142669ce2786 --- /dev/null +++ b/sdk/ai/azure-ai-agents/src/test/java/com/azure/ai/agents/models/VersionSelectorTests.java @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.agents.models; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +public class VersionSelectorTests { + + @Test + public void setVersionSelectionRuleWrapsRuleInList() { + VersionSelectionRule rule = new FixedRatioVersionSelectionRule(100).setAgentVersion("1"); + + VersionSelector selector = new VersionSelector().setVersionSelectionRule(rule); + + assertEquals(1, selector.getVersionSelectionRules().size()); + assertSame(rule, selector.getVersionSelectionRules().get(0)); + } +} From 596d1363c323e5e10e30a35dc7a42befe263b0e3 Mon Sep 17 00:00:00 2001 From: kaylieee Date: Wed, 16 Sep 2026 02:00:59 -0700 Subject: [PATCH 17/17] add checkstyle suppression --- sdk/ai/azure-ai-agents/checkstyle-suppressions.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/ai/azure-ai-agents/checkstyle-suppressions.xml b/sdk/ai/azure-ai-agents/checkstyle-suppressions.xml index 196eacab984b8..66e9217e62810 100644 --- a/sdk/ai/azure-ai-agents/checkstyle-suppressions.xml +++ b/sdk/ai/azure-ai-agents/checkstyle-suppressions.xml @@ -5,6 +5,7 @@ +