Skip to content

Commit ac26c56

Browse files
committed
updating code
1 parent 60e52e4 commit ac26c56

File tree

1 file changed

+87
-101
lines changed

1 file changed

+87
-101
lines changed

articles/ai-foundry/agents/includes/quickstart-java.md

Lines changed: 87 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,6 @@
2929
<artifactId>azure-identity</artifactId>
3030
<version>1.17.0-beta.1</version>
3131
</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>
4232
</dependencies>
4333
```
4434

@@ -56,122 +46,118 @@ Use the following code to create and run an agent. To run this code, you will ne
5646

5747
[!INCLUDE [endpoint-string-portal](endpoint-string-portal.md)]
5848

59-
Set this endpoint in an environment variable named `ProjectEndpoint`.
49+
Set this endpoint in an environment variable named `PROJECT_ENDPOINT`.
6050

6151
[!INCLUDE [model-name-portal](model-name-portal.md)]
6252

63-
Save the name of your model deployment name as an environment variable named `ModelDeploymentName`.
53+
Save the name of your model deployment name as an environment variable named `MODEL_DEPLOYMENT_NAME`.
6454

6555
## Code example
6656

6757
```java
6858
package com.example.agents;
6959

60+
import com.azure.ai.agents.persistent.MessagesClient;
61+
import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient;
7062
import com.azure.ai.agents.persistent.PersistentAgentsClient;
7163
import com.azure.ai.agents.persistent.PersistentAgentsClientBuilder;
72-
import com.azure.ai.agents.persistent.PersistentAgentsAdministrationClient;
64+
import com.azure.ai.agents.persistent.RunsClient;
65+
import com.azure.ai.agents.persistent.ThreadsClient;
66+
import com.azure.ai.agents.persistent.models.CodeInterpreterToolDefinition;
7367
import com.azure.ai.agents.persistent.models.CreateAgentOptions;
74-
import com.azure.ai.agents.persistent.models.CreateThreadAndRunOptions;
68+
import com.azure.ai.agents.persistent.models.CreateRunOptions;
69+
import com.azure.ai.agents.persistent.models.MessageImageFileContent;
70+
import com.azure.ai.agents.persistent.models.MessageRole;
71+
import com.azure.ai.agents.persistent.models.MessageTextContent;
7572
import com.azure.ai.agents.persistent.models.PersistentAgent;
73+
import com.azure.ai.agents.persistent.models.PersistentAgentThread;
74+
import com.azure.ai.agents.persistent.models.RunStatus;
75+
import com.azure.ai.agents.persistent.models.ThreadMessage;
7676
import com.azure.ai.agents.persistent.models.ThreadRun;
77-
import com.azure.core.credential.TokenCredential;
78-
import com.azure.core.exception.HttpResponseException;
79-
import com.azure.core.util.logging.ClientLogger;
77+
import com.azure.ai.agents.persistent.models.MessageContent;
78+
import com.azure.core.http.rest.PagedIterable;
8079
import com.azure.identity.DefaultAzureCredentialBuilder;
80+
import java.util.Arrays;
8181

8282
public class Main {
83-
private static final ClientLogger logger = new ClientLogger(Main.class);
8483

85-
public static void main(String[] args) {
86-
// Load environment variables with better error handling, supporting both .env and system environment variables
87-
String endpoint = System.getenv("AZURE_ENDPOINT");
88-
String projectEndpoint = System.getenv("PROJECT_ENDPOINT");
89-
String modelName = System.getenv("MODEL_DEPLOYMENT_NAME");
90-
String agentName = System.getenv("AGENT_NAME");
91-
String instructions = "You are a helpful assistant that provides clear and concise information.";
92-
93-
// Check for required endpoint configuration
94-
if (projectEndpoint == null && endpoint == null) {
95-
String errorMessage = "Environment variables not configured. Required: either PROJECT_ENDPOINT or AZURE_ENDPOINT must be set.";
96-
logger.error("ERROR: {}", errorMessage);
97-
logger.error("Please set your environment variables or create a .env file. See README.md for details.");
98-
return;
99-
}
100-
101-
// Use AZURE_ENDPOINT as fallback if PROJECT_ENDPOINT not set
102-
if (projectEndpoint == null) {
103-
projectEndpoint = endpoint;
104-
logger.info("Using AZURE_ENDPOINT as PROJECT_ENDPOINT: {}", projectEndpoint);
84+
public static void printRunMessages(MessagesClient messagesClient, String threadId) {
85+
86+
PagedIterable<ThreadMessage> runMessages = messagesClient.listMessages(threadId);
87+
for (ThreadMessage message : runMessages) {
88+
System.out.print(String.format("%1$s - %2$s : ", message.getCreatedAt(), message.getRole()));
89+
for (MessageContent contentItem : message.getContent()) {
90+
if (contentItem instanceof MessageTextContent) {
91+
System.out.print((((MessageTextContent) contentItem).getText().getValue()));
92+
} else if (contentItem instanceof MessageImageFileContent) {
93+
String imageFileId = (((MessageImageFileContent) contentItem).getImageFile().getFileId());
94+
System.out.print("Image from ID: " + imageFileId);
95+
}
96+
System.out.println();
97+
}
10598
}
99+
}
100+
public static void waitForRunCompletion(String threadId, ThreadRun threadRun, RunsClient runsClient)
101+
throws InterruptedException {
106102

107-
// Set defaults for optional parameters with informative logging
108-
if (modelName == null) {
109-
modelName = "gpt-4o";
110-
logger.info("No MODEL_DEPLOYMENT_NAME provided, using default: {}", modelName);
111-
}
112-
if (agentName == null) {
113-
agentName = "java-quickstart-agent";
114-
logger.info("No AGENT_NAME provided, using default: {}", agentName);
103+
// BEGIN: com.azure.ai.agents.persistent.SampleUtils.waitForRunCompletion
104+
105+
do {
106+
Thread.sleep(500);
107+
threadRun = runsClient.getRun(threadId, threadRun.getId());
115108
}
116-
if (instructions == null) {
117-
instructions = "You are a helpful assistant that provides clear and concise information.";
118-
logger.info("No AGENT_INSTRUCTIONS provided, using default instructions");
109+
while (
110+
threadRun.getStatus() == RunStatus.QUEUED
111+
|| threadRun.getStatus() == RunStatus.IN_PROGRESS
112+
|| threadRun.getStatus() == RunStatus.REQUIRES_ACTION);
113+
114+
if (threadRun.getStatus() == RunStatus.FAILED) {
115+
System.out.println(threadRun.getLastError().getMessage());
119116
}
120117

121-
// Create Azure credential with DefaultAzureCredentialBuilder
122-
// This supports multiple authentication methods including environment variables,
123-
// managed identities, and interactive browser login
124-
logger.info("Building DefaultAzureCredential");
125-
TokenCredential credential = new DefaultAzureCredentialBuilder().build();
118+
// END: com.azure.ai.agents.persistent.SampleUtils.waitForRunCompletion
119+
}
120+
public static void main(String[] args) {
126121

127-
try {
128-
// Build the general agents client
129-
logger.info("Creating PersistentAgentsClient with endpoint: {}", projectEndpoint);
130-
PersistentAgentsClient agentsClient = new PersistentAgentsClientBuilder()
131-
.endpoint(projectEndpoint)
132-
.credential(credential)
133-
.buildClient();
134-
135-
// Derive the administration client
136-
logger.info("Getting PersistentAgentsAdministrationClient");
137-
PersistentAgentsAdministrationClient adminClient =
138-
agentsClient.getPersistentAgentsAdministrationClient();
139-
140-
// Create an agent
141-
logger.info("Creating agent with name: {}, model: {}", agentName, modelName);
142-
PersistentAgent agent = adminClient.createAgent(
143-
new CreateAgentOptions(modelName)
144-
.setName(agentName)
145-
.setInstructions(instructions)
146-
);
147-
logger.info("Agent created: ID={}, Name={}", agent.getId(), agent.getName());
148-
logger.info("Agent model: {}", agent.getModel());
149-
150-
// Start a thread/run on the general client
151-
logger.info("Creating thread and run with agent ID: {}", agent.getId());
152-
ThreadRun runResult = agentsClient.createThreadAndRun(
153-
new CreateThreadAndRunOptions(agent.getId())
154-
);
155-
logger.info("ThreadRun created: ThreadId={}", runResult.getThreadId());
156-
157-
// List available getters on ThreadRun for informational purposes
158-
logger.info("\nAvailable getters on ThreadRun:");
159-
for (var method : ThreadRun.class.getMethods()) {
160-
if (method.getName().startsWith("get")) {
161-
logger.info(" - {}", method.getName());
162-
}
163-
}
122+
String projectEndpoint = System.getenv("PROJECT_ENDPOINT");
123+
String modelName = System.getenv("MODEL_DEPLOYMENT_NAME");
124+
125+
PersistentAgentsClientBuilder clientBuilder = new PersistentAgentsClientBuilder()
126+
.endpoint(projectEndpoint)
127+
.credential(new DefaultAzureCredentialBuilder().build());
128+
PersistentAgentsClient agentsClient = clientBuilder.buildClient();
129+
PersistentAgentsAdministrationClient administrationClient = agentsClient.getPersistentAgentsAdministrationClient();
130+
ThreadsClient threadsClient = agentsClient.getThreadsClient();
131+
MessagesClient messagesClient = agentsClient.getMessagesClient();
132+
RunsClient runsClient = agentsClient.getRunsClient();
133+
134+
String agentName = "my-agent";
135+
CreateAgentOptions createAgentOptions = new CreateAgentOptions(modelName)
136+
.setName(agentName)
137+
.setInstructions("You are a helpful agent")
138+
.setTools(Arrays.asList(new CodeInterpreterToolDefinition()));
139+
PersistentAgent agent = administrationClient.createAgent(createAgentOptions);
140+
141+
PersistentAgentThread thread = threadsClient.createThread();
142+
ThreadMessage createdMessage = messagesClient.createMessage(
143+
thread.getId(),
144+
MessageRole.USER,
145+
"I need to solve the equation `3x + 11 = 14`. Can you help me?");
164146

165-
logger.info("\nDemo completed successfully!");
166-
167-
} catch (HttpResponseException e) {
168-
// Handle service-specific errors with detailed information
169-
int statusCode = e.getResponse().getStatusCode();
170-
logger.error("Service error {}: {}", statusCode, e.getMessage());
171-
logger.error("Refer to the Azure AI Agents documentation for troubleshooting information.");
172-
} catch (Exception e) {
173-
// Handle general exceptions
174-
logger.error("Error in agent sample: {}", e.getMessage(), e);
147+
try {
148+
//run agent
149+
CreateRunOptions createRunOptions = new CreateRunOptions(thread.getId(), agent.getId())
150+
.setAdditionalInstructions("");
151+
ThreadRun threadRun = runsClient.createRun(createRunOptions);
152+
153+
waitForRunCompletion(thread.getId(), threadRun, runsClient);
154+
printRunMessages(messagesClient, thread.getId());
155+
} catch (InterruptedException e) {
156+
throw new RuntimeException(e);
157+
} finally {
158+
//cleanup
159+
threadsClient.deleteThread(thread.getId());
160+
administrationClient.deleteAgent(agent.getId());
175161
}
176162
}
177163
}

0 commit comments

Comments
 (0)