|
| 1 | + |
| 2 | +| [Reference documentation](/dotnet/api/overview/azure/ai.agents.persistent-readme) | [Samples](https://github.com/azure-ai-foundry/foundry-samples/tree/main/samples/microsoft/csharp/getting-started-agents) | [Library source code](https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent) | [Package (NuGet)](https://www.nuget.org/packages/Azure.AI.Agents.Persistent) | |
| 3 | + |
| 4 | +## Prerequisites |
| 5 | + |
| 6 | +[!INCLUDE [universal-prerequisites](universal-prerequisites.md)] |
| 7 | + |
| 8 | +## Configure and run an agent |
| 9 | + |
| 10 | +| Component | Description | |
| 11 | +| --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | |
| 12 | +| Agent | Custom AI that uses AI models in conjunction with tools. | |
| 13 | +| Tool | Tools help extend an agent’s ability to reliably and accurately respond during conversation. Such as connecting to user-defined knowledge bases to ground the model, or enabling web search to provide current information. | |
| 14 | +| Thread | A conversation session between an agent and a user. Threads store Messages and automatically handle truncation to fit content into a model’s context. | |
| 15 | +| Message | A message created by an agent or a user. Messages can include text, images, and other files. Messages are stored as a list on the Thread. | |
| 16 | +| Run | Activation of an agent to begin running based on the contents of Thread. The agent uses its configuration and Thread’s Messages to perform tasks by calling models and tools. As part of a Run, the agent appends Messages to the Thread. | |
| 17 | + |
| 18 | +1. Create a New Java Console project. You will need the following dependencies to run the code: |
| 19 | + |
| 20 | + ```xml |
| 21 | + <dependencies> |
| 22 | + <dependency> |
| 23 | + <groupId>com.azure</groupId> |
| 24 | + <artifactId>azure-ai-agents-persistent</artifactId> |
| 25 | + <version>1.0.0-beta.2</version> |
| 26 | + </dependency> |
| 27 | + <dependency> |
| 28 | + <groupId>com.azure</groupId> |
| 29 | + <artifactId>azure-identity</artifactId> |
| 30 | + <version>1.17.0-beta.1</version> |
| 31 | + </dependency> |
| 32 | + <dependency> |
| 33 | + <groupId>org.slf4j</groupId> |
| 34 | + <artifactId>slf4j-api</artifactId> |
| 35 | + <version>1.7.32</version> |
| 36 | + </dependency> |
| 37 | + <dependency> |
| 38 | + <groupId>org.slf4j</groupId> |
| 39 | + <artifactId>slf4j-simple</artifactId> |
| 40 | + <version>1.7.32</version> |
| 41 | + </dependency> |
| 42 | + </dependencies> |
| 43 | + ``` |
| 44 | + |
| 45 | +Next, to authenticate your API requests and run the program, use the [az login](/cli/azure/authenticate-azure-cli-interactively) command to sign into your Azure subscription. |
| 46 | + |
| 47 | +```azurecli |
| 48 | +az login |
| 49 | +``` |
| 50 | + |
| 51 | +Use the following code to create and run an agent. To run this code, you will need to get the endpoint for your project. This string is in the format: |
| 52 | + |
| 53 | +`https://<AIFoundryResourceName>.services.ai.azure.com/api/projects/<ProjectName>` |
| 54 | + |
| 55 | +[!INCLUDE [connection-string-deprecation](connection-string-deprecation.md)] |
| 56 | + |
| 57 | +[!INCLUDE [endpoint-string-portal](endpoint-string-portal.md)] |
| 58 | + |
| 59 | +Set this endpoint in an environment variable named `ProjectEndpoint`. |
| 60 | + |
| 61 | +[!INCLUDE [model-name-portal](model-name-portal.md)] |
| 62 | + |
| 63 | +Save the name of your model deployment name as an environment variable named `ModelDeploymentName`. |
| 64 | + |
| 65 | + |
| 66 | +```java |
| 67 | +package com.example.agents; |
| 68 | + |
| 69 | +import com.azure.ai.agents.persistent.PersistentAgentsClient; |
| 70 | +import com.azure.ai.agents.persistent.PersistentAgentsClientBuilder; |
| 71 | +import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient; |
| 72 | +import com.azure.ai.agents.persistent.models.CreateAgentOptions; |
| 73 | +import com.azure.ai.agents.persistent.models.CreateThreadAndRunOptions; |
| 74 | +import com.azure.ai.agents.persistent.models.PersistentAgent; |
| 75 | +import com.azure.ai.agents.persistent.models.ThreadRun; |
| 76 | +import com.azure.core.credential.TokenCredential; |
| 77 | +import com.azure.core.exception.HttpResponseException; |
| 78 | +import com.azure.core.util.logging.ClientLogger; |
| 79 | +import com.azure.identity.DefaultAzureCredentialBuilder; |
| 80 | + |
| 81 | +public class Main { |
| 82 | + private static final ClientLogger logger = new ClientLogger(Main.class); |
| 83 | + |
| 84 | + public static void main(String[] args) { |
| 85 | + // Load environment variables with better error handling, supporting both .env and system environment variables |
| 86 | + String endpoint = System.getenv("AZURE_ENDPOINT"); |
| 87 | + String projectEndpoint = System.getenv("PROJECT_ENDPOINT"); |
| 88 | + String modelName = System.getenv("MODEL_DEPLOYMENT_NAME"); |
| 89 | + String agentName = System.getenv("AGENT_NAME"); |
| 90 | + String instructions = "You are a helpful assistant that provides clear and concise information."; |
| 91 | + |
| 92 | + // Check for required endpoint configuration |
| 93 | + if (projectEndpoint == null && endpoint == null) { |
| 94 | + String errorMessage = "Environment variables not configured. Required: either PROJECT_ENDPOINT or AZURE_ENDPOINT must be set."; |
| 95 | + logger.error("ERROR: {}", errorMessage); |
| 96 | + logger.error("Please set your environment variables or create a .env file. See README.md for details."); |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + // Use AZURE_ENDPOINT as fallback if PROJECT_ENDPOINT not set |
| 101 | + if (projectEndpoint == null) { |
| 102 | + projectEndpoint = endpoint; |
| 103 | + logger.info("Using AZURE_ENDPOINT as PROJECT_ENDPOINT: {}", projectEndpoint); |
| 104 | + } |
| 105 | + |
| 106 | + // Set defaults for optional parameters with informative logging |
| 107 | + if (modelName == null) { |
| 108 | + modelName = "gpt-4o"; |
| 109 | + logger.info("No MODEL_DEPLOYMENT_NAME provided, using default: {}", modelName); |
| 110 | + } |
| 111 | + if (agentName == null) { |
| 112 | + agentName = "java-quickstart-agent"; |
| 113 | + logger.info("No AGENT_NAME provided, using default: {}", agentName); |
| 114 | + } |
| 115 | + if (instructions == null) { |
| 116 | + instructions = "You are a helpful assistant that provides clear and concise information."; |
| 117 | + logger.info("No AGENT_INSTRUCTIONS provided, using default instructions"); |
| 118 | + } |
| 119 | + |
| 120 | + // Create Azure credential with DefaultAzureCredentialBuilder |
| 121 | + // This supports multiple authentication methods including environment variables, |
| 122 | + // managed identities, and interactive browser login |
| 123 | + logger.info("Building DefaultAzureCredential"); |
| 124 | + TokenCredential credential = new DefaultAzureCredentialBuilder().build(); |
| 125 | + |
| 126 | + try { |
| 127 | + // Build the general agents client |
| 128 | + logger.info("Creating PersistentAgentsClient with endpoint: {}", projectEndpoint); |
| 129 | + PersistentAgentsClient agentsClient = new PersistentAgentsClientBuilder() |
| 130 | + .endpoint(projectEndpoint) |
| 131 | + .credential(credential) |
| 132 | + .buildClient(); |
| 133 | + |
| 134 | + // Derive the administration client |
| 135 | + logger.info("Getting PersistentAgentsAdministrationClient"); |
| 136 | + PersistentAgentsAdministrationClient adminClient = |
| 137 | + agentsClient.getPersistentAgentsAdministrationClient(); |
| 138 | + |
| 139 | + // Create an agent |
| 140 | + logger.info("Creating agent with name: {}, model: {}", agentName, modelName); |
| 141 | + PersistentAgent agent = adminClient.createAgent( |
| 142 | + new CreateAgentOptions(modelName) |
| 143 | + .setName(agentName) |
| 144 | + .setInstructions(instructions) |
| 145 | + ); |
| 146 | + logger.info("Agent created: ID={}, Name={}", agent.getId(), agent.getName()); |
| 147 | + logger.info("Agent model: {}", agent.getModel()); |
| 148 | + |
| 149 | + // Start a thread/run on the general client |
| 150 | + logger.info("Creating thread and run with agent ID: {}", agent.getId()); |
| 151 | + ThreadRun runResult = agentsClient.createThreadAndRun( |
| 152 | + new CreateThreadAndRunOptions(agent.getId()) |
| 153 | + ); |
| 154 | + logger.info("ThreadRun created: ThreadId={}", runResult.getThreadId()); |
| 155 | + |
| 156 | + // List available getters on ThreadRun for informational purposes |
| 157 | + logger.info("\nAvailable getters on ThreadRun:"); |
| 158 | + for (var method : ThreadRun.class.getMethods()) { |
| 159 | + if (method.getName().startsWith("get")) { |
| 160 | + logger.info(" - {}", method.getName()); |
| 161 | + } |
| 162 | + } |
| 163 | + |
| 164 | + logger.info("\nDemo completed successfully!"); |
| 165 | + |
| 166 | + } catch (HttpResponseException e) { |
| 167 | + // Handle service-specific errors with detailed information |
| 168 | + int statusCode = e.getResponse().getStatusCode(); |
| 169 | + logger.error("Service error {}: {}", statusCode, e.getMessage()); |
| 170 | + logger.error("Refer to the Azure AI Agents documentation for troubleshooting information."); |
| 171 | + } catch (Exception e) { |
| 172 | + // Handle general exceptions |
| 173 | + logger.error("Error in agent sample: {}", e.getMessage(), e); |
| 174 | + } |
| 175 | + } |
| 176 | +} |
| 177 | +``` |
0 commit comments