Unlike the previous code section, we’re going to look at the code in the online VS code development environment as to use agents on your own computer, you need to set up an azure development environment. To access this code, go into the agent playground and click the ‘view code’ button on the top button.
We can begin as usual by importing the relevant libraries. If you need to check what libraries you need for your local machine, you can see them in the requirement.txt file located in vs code training environment.
# Import required libraries
from typing import Optional
from azure.core.credentials import AccessToken
from azure.ai.projects import AIProjectClient
from azure.ai.agents.models import ListSortOrder
After this we need to set up the Project Client. In this code the credential is found for us, but we need to specify the end point.
# Set up the Project Client
project_client = AIProjectClient(
credential=AIProjectClient()
endpoint="https://test-tutorial-2-resource.services.ai.azure.com/api/projects/test-tutorial-2-resourc-project")
# replace with your endpoint URL
After specifying where to find the agent, we need to locate the agent specifically and the thread.
# Locate agent and thread
agent = project.agents.get_agent("ass_vFSidjnsiCJOCS125nI")# Replace with your own
thread = project.agents.threads.get("thread_eCSI2dmsJOJc9")# Replace with your own
After locating the agent and thread, we need to create the message. Within this store message, we need to specify the thread and the role of the machine the message is originating from.
# Create and store message
message = project.agents.messages.create(
thread_id=thread_id,
role="user",
content="Hello Agent"
)
Folling our message, we need to create a new run using the agent ID and the thread ID
# Create a new run
run = project.agents.runs.create_and_process(
thread_id=thread.id,
agent_id=agent.id
)
Lastly, we pull all the messages from our agent and loop through sending them to the agent.
# Retrieve and process messages
if run.status == "failed":
print(f"Run failed: {run.last_error}")
else:
messages = project.agents.messages_list(thread_id=thread.id, order=ListSortOrder.ASCENDING)
for message in messages:
if message.text_messages:
print(f"{message.role}: {message.text_messages[-1].text.value}")