diff --git a/supporting-blog-content/agent-builder-a2a-strands-agents/Dockerfile b/supporting-blog-content/agent-builder-a2a-strands-agents/Dockerfile new file mode 100644 index 00000000..91609977 --- /dev/null +++ b/supporting-blog-content/agent-builder-a2a-strands-agents/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.11-slim + +WORKDIR /app + +RUN python -m venv /opt/venv + +ENV PATH="/opt/venv/bin:$PATH" + +COPY requirements.txt . + +RUN pip install -r requirements.txt + +COPY elastic_agent_builder_a2a_rps+.py . + +CMD ["python", "elastic_agent_builder_a2a_rps+.py"] \ No newline at end of file diff --git a/supporting-blog-content/agent-builder-a2a-strands-agents/README.md b/supporting-blog-content/agent-builder-a2a-strands-agents/README.md new file mode 100644 index 00000000..b453e031 --- /dev/null +++ b/supporting-blog-content/agent-builder-a2a-strands-agents/README.md @@ -0,0 +1,185 @@ +# Elastic Agent Builder A2A Example App : RTG+ (Rock Paper Scissors +) + +**Getting started with Agent Builder and A2A using Strands Agents SDK** + +This is an example Python console app that demonstrates how to connect and utilize an [Elastic Agent Builder](https://www.elastic.co/elasticsearch/agent-builder) agent via the Agent2Agent (A2A) Protocol orchestrated with the [Strands Agents SDK](https://strandsagents.com). + +## Prerequisites + +1. An Elasticsearch project/deployment running in [Elastic Cloud](https://cloud.elastic.co/registration?utm_source=github&utm_content=elasticsearch-labs-example-apps). + * Requires Elasticsearch serverless project (or for hosted deployments at least Elasticsearch version 9.2.0). +2. A text editor or an integrated development environment (IDE) like [Visual Studio Code](https://code.visualstudio.com/download) running on your local computer. +3. [Python version 3.10 or greater](https://www.python.org/downloads/) installed on your local computer. + +## Set up your Elasticsearch project + +1. Create an index named `game-docs` in your Elasticsearch project by running the following command in Elastic Developer Tools: + + PUT /game-docs + { + "mappings": { + "properties": { + "title": { "type": "text" }, + "content": { + "type": "text" + }, + "filename": { "type": "keyword" }, + "last_modified": { "type": "date" } + } + } + } +2. Insert a document into your index named `RPS+.md` by running the following command in Elastic Developer Tools: + + PUT /game-docs/_doc/rps+-md + { + "title": "Rock Paper Scissors +", + "content": " + # Game Name + RPS+ + + # Starting Prompt + Let's play RPS+ ! + --- + What do you choose? + + # Game Objects + 1. Rock 🪨 👊 + 2. Paper 📜 🖐 + 3. Scissors ✄ ✌️ + 4. Light ☼ 👍 + 5. Dark Energy ☄ 🫱 + + # Judgement of Victory + * Rock beats Scissors + * because rocks break scissors + * Paper beats Rock + * because paper covers rock + * Scissors beat Paper + * because scissors cut paper + * Rock beats Light + * because you can build a rock structure to block out light + * Paper beats Light + * because knowledge stored in files and paper books helps us understand light + * Light beats Dark Energy + * because light enables humans to lighten up and laugh in the face of dark energy as it causes the eventual heat death of the universe + * Light beats Scissors + * because light is needed to use scissors safely + * Dark Energy beats Rock + * because dark energy rocks more than rocks. It rocks rocks and everything else in its expansion of the universe + * Dark Energy beats Paper + * because humans, with their knowledge stored in files and paper books, can't explain dark energy + * Scissors beat Dark Energy + * because a human running with scissors is darker than dark energy + + # Invalid Input + I was hoping for an worthy opponent + - but alas it appears that time has past + - but alas there's little time for your todo list when [todo:fix this] is so vast + + # Cancel Game + The future belongs to the bold. Goodbye.. + + ", + "filename": "RPS+.md", + "last_modified": "2025-11-25T12:00:00Z" + } + +3. In Elastic Agent Builder, create a **tool** with the following values: +* **Type**: `ES|QL` +* **Tool ID**: `example.get_game_docs` +* **Description**: `Get RPS+ doc from Elasticsearch game-docs index.` +* **ES|QL**: + + FROM game-docs | WHERE filename == "RPS+.md" + +1. In Elastic Agent Builder, create an **agent** with the following values: +* **Agent ID**: `rps_plus_agent` +* **Custom Instructions**: + + When prompted, if the prompt contains an integer, then select the corresponding numbered item in the list of "Game Objects" from your documents. Otherwise select a random game object. This is your chosen game object for a single round of the game. + + # General Game Rules + * 2 players + - the user: the person playing the game + - you: the agent playing the game and serving as the game master + * Each player chooses a game object which will be compared and cause them to tie, win or lose. + + # Start the game + 1. This is the way each new game always starts. You make the first line of your response only the name of your chosen game object. + + 2. The remainder of your response should be the "Starting Prompt" text from your documents and generate a list of "Game Objects" for the person playing the game to choose a game object from. + + # End of Game: The game ends in one of the following three outcomes: + 3. Invalid Input: If the player responds with an invalid game object choice, respond with variations of the "Invalid Input" text from your documents and then end the game. + + 4. Tie: The game ends in a tie if the user chooses the same game object as your game object choice. + + 5. Win or Lose: The game winner is decided based on the "Judgement of Victory" conditions from your documents. Compare the user's game object choice and your game object choice and determine who chose the winning game object. + + # Game conclusion + Respond with a declaration of the winner of the game by outputting the corresponding text in the "Judgement of Victory" section of your documents. + +* **Display Name**: `RPS+ Agent` +* **Display Description**: `An agent that plays the game RPS+` + + + +## Clone the example app + +1. Open a terminal and clone the Search Labs source code repository which contains the Elastic Agent Builder A2A App example: RPS+. Run the following command to clone the example app: + + git clone https://github.com/elastic/elasticsearch-labs + +3. `cd` to change directory to the example code located in the `supporting-blog-content/agent-builder-a2a-strands-agents` subdirectory. + + cd elasticsearch-labs/supporting-blog-content/agent-builder-a2a-strands-agents + +## Set up the environment variables + +1. Set up the environment variables with values copied from your Elastic project. + 1. Make a copy of the file `env.example` and name the new file `.env ` + 2. Edit the `.env` file to set the values of the environment variables to use the values copied from your Elastic project. + * Replace + 1. In your Elastic project, go to the Elastic Agent Builder - Tools page. Click the **MCP Server** dropdown at the top of the Tools page. Select **Copy MCP Server URL.** + 2. Add the **MCP Server URL** value to the `.env` file. + * Find where the placeholder text “****” appears and paste in the copied **MCP Server URL** to replace the placeholder text. Now edit the pasted **MCP Server URL**. Delete the text “mcp” at the end of the URL and replace it with the text “a2a”. The edited URL should look something like this + + `https://rps-game-project-12345a.kb.us-east-1.aws.elastic.cloud/api/agent_builder/a2a` + + * Replace + 1. In your Elastic project, click **Elasticsearch** in the navigation menu to go to your project’s home page. + 2. Click **Create API key** to create a new API key. + 3. After the API key is created, copy the API Key value. + 4. Add the API Key value to the `.env` file. + * Find where the placeholder text “****” appears and paste in the copied API Key value to replace the placeholder text. + + 3. Save the changes to the `.env` file. + +## Running the example app with Python + +1. Create a Python virtual environment by running the following code in the terminal. + + python -m venv .venv + +2. Activate the Python virtual environment. + * If you’re running MacOS, the command to activate the virtual environment is: + + source .venv/bin/activate + + * If you’re on Windows, the command to activate the virtual environment is: + + .venv\Scripts\activate + +3. Install the [Strands Agents SDK](https://strandsagents.com) along with its necessary Python packages by running the following `pip` command: + + pip install -r requirements.txt + +4. Run the example app by entering the following command into the terminal: + + python elastic_agent_builder_a2a_rps+.py + +## Running the example app with Docker + +1. Run the example app with Docker by entering the following command into the terminal: + + docker compose run elastic-agent-builder-a2a-strands-agents diff --git a/supporting-blog-content/agent-builder-a2a-strands-agents/docker-compose.yml b/supporting-blog-content/agent-builder-a2a-strands-agents/docker-compose.yml new file mode 100644 index 00000000..608155f6 --- /dev/null +++ b/supporting-blog-content/agent-builder-a2a-strands-agents/docker-compose.yml @@ -0,0 +1,9 @@ +services: + elastic-agent-builder-a2a-strands-agents: + build: . + container_name: elastic-agent-builder-a2a-strands-agents + stdin_open: true + tty: true + environment: + - ES_AGENT_URL=${ES_AGENT_URL} + - ES_API_KEY=${ES_API_KEY} \ No newline at end of file diff --git a/supporting-blog-content/agent-builder-a2a-strands-agents/elastic_agent_builder_a2a_rps+.py b/supporting-blog-content/agent-builder-a2a-strands-agents/elastic_agent_builder_a2a_rps+.py new file mode 100644 index 00000000..1c8d0ee1 --- /dev/null +++ b/supporting-blog-content/agent-builder-a2a-strands-agents/elastic_agent_builder_a2a_rps+.py @@ -0,0 +1,66 @@ +import asyncio +from dotenv import load_dotenv +from uuid import uuid4 +import httpx +import os +import random +from a2a.client import A2ACardResolver, ClientConfig, ClientFactory +from a2a.types import Message, Part, Role, TextPart + +DEFAULT_TIMEOUT = 60 # set request timeout to 1 minute + + +def create_message(*, role: Role = Role.user, text: str, context_id=None) -> Message: + return Message( + kind="message", + role="user", + parts=[Part(TextPart(kind="text", text=text))], + message_id=uuid4().hex, + context_id=context_id, + ) + + +async def main(): + load_dotenv() + a2a_agent_host = os.getenv("ES_AGENT_URL") + a2a_agent_key = os.getenv("ES_API_KEY") + custom_headers = {"Authorization": f"ApiKey {a2a_agent_key}"} + + async with httpx.AsyncClient( + timeout=DEFAULT_TIMEOUT, headers=custom_headers + ) as httpx_client: + # Get agent card + resolver = A2ACardResolver(httpx_client=httpx_client, base_url=a2a_agent_host) + agent_card = await resolver.get_agent_card( + relative_card_path="/rps_plus_agent.json" + ) + # Create client using factory + config = ClientConfig( + httpx_client=httpx_client, + streaming=True, + ) + factory = ClientFactory(config) + client = factory.create(agent_card) + # Use the client to communicate with the agent + print("\nSending 'start game' message to Elastic A2A agent...") + random_game_object = random.randint(1, 5) + msg = create_message(text=f"start with game object {random_game_object}") + async for event in client.send_message(msg): + if isinstance(event, Message): + context_id = event.context_id + response_complete = event.parts[0].root.text + # Get agent choice from the first line of the response + parsed_response = response_complete.split("\n", 1) + agent_choice = parsed_response[0] + print(parsed_response[1]) + # User choice sent for game results from the agent + prompt = input("Your Choice : ") + msg = create_message(text=prompt, context_id=context_id) + async for event in client.send_message(msg): + if isinstance(event, Message): + print(f"Agent Choice : {agent_choice}") + print(event.parts[0].root.text) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/supporting-blog-content/agent-builder-a2a-strands-agents/env.example b/supporting-blog-content/agent-builder-a2a-strands-agents/env.example new file mode 100644 index 00000000..a857c0fd --- /dev/null +++ b/supporting-blog-content/agent-builder-a2a-strands-agents/env.example @@ -0,0 +1,2 @@ +ES_AGENT_URL= +ES_API_KEY= \ No newline at end of file diff --git a/supporting-blog-content/agent-builder-a2a-strands-agents/requirements.txt b/supporting-blog-content/agent-builder-a2a-strands-agents/requirements.txt new file mode 100644 index 00000000..a4ab9187 --- /dev/null +++ b/supporting-blog-content/agent-builder-a2a-strands-agents/requirements.txt @@ -0,0 +1,100 @@ +a2a-sdk==0.3.20 +aiohappyeyeballs==2.6.1 +aiohttp==3.13.2 +aiomysql==0.3.2 +aiosignal==1.4.0 +aiosqlite==0.21.0 +annotated-doc==0.0.4 +annotated-types==0.7.0 +anyio==4.12.0 +asyncpg==0.31.0 +attrs==25.4.0 +aws-requests-auth==0.4.3 +beautifulsoup4==4.14.3 +boto3==1.42.4 +botocore==1.42.4 +cachetools==6.2.2 +certifi==2025.11.12 +cffi==2.0.0 +charset-normalizer==3.4.4 +click==8.3.1 +colorama==0.4.6 +cryptography==46.0.3 +dill==0.4.0 +docstring_parser==0.17.0 +fastapi==0.123.10 +frozenlist==1.8.0 +google-api-core==2.28.1 +google-auth==2.43.0 +googleapis-common-protos==1.72.0 +greenlet==3.3.0 +h11==0.16.0 +halo==0.0.31 +httpcore==1.0.9 +httpx==0.28.1 +httpx-sse==0.4.3 +idna==3.11 +importlib_metadata==8.7.0 +jmespath==1.0.1 +jsonschema==4.25.1 +jsonschema-specifications==2025.9.1 +log-symbols==0.0.14 +markdown-it-py==4.0.0 +markdownify==1.2.2 +mcp==1.23.1 +mdurl==0.1.2 +mpmath==1.3.0 +multidict==6.7.0 +ollama==0.6.1 +opentelemetry-api==1.39.0 +opentelemetry-instrumentation==0.60b0 +opentelemetry-instrumentation-threading==0.60b0 +opentelemetry-sdk==1.39.0 +opentelemetry-semantic-conventions==0.60b0 +packaging==25.0 +pillow==11.3.0 +prompt_toolkit==3.0.52 +propcache==0.4.1 +proto-plus==1.26.1 +protobuf==6.33.1 +pyasn1==0.6.1 +pyasn1_modules==0.4.2 +pycparser==2.23 +pydantic==2.12.5 +pydantic-settings==2.12.0 +pydantic_core==2.41.5 +Pygments==2.19.2 +PyJWT==2.10.1 +PyMySQL==1.1.2 +python-dateutil==2.9.0.post0 +python-dotenv==1.2.1 +python-multipart==0.0.20 +referencing==0.37.0 +requests==2.32.5 +rich==14.2.0 +rpds-py==0.30.0 +rsa==4.9.1 +s3transfer==0.16.0 +six==1.17.0 +slack_bolt==1.27.0 +slack_sdk==3.39.0 +soupsieve==2.8 +spinners==0.0.24 +SQLAlchemy==2.0.44 +sse-starlette==3.0.3 +starlette==0.50.0 +strands-agents==1.19.0 +strands-agents-builder==0.1.10 +strands-agents-tools==0.2.17 +sympy==1.14.0 +tenacity==9.1.2 +termcolor==3.2.0 +typing-inspection==0.4.2 +typing_extensions==4.15.0 +urllib3==2.6.0 +uvicorn==0.38.0 +watchdog==6.0.0 +wcwidth==0.2.14 +wrapt==1.17.3 +yarl==1.22.0 +zipp==3.23.0