
Building Production-Ready AI Agents with Web Capabilities
A Complete Guide to Tavily, Strands SDK with multi-agent collaboration, and Amazon Bedrock AgentCore
This tutorial demonstrates how to build production-ready AI agents with the capability to search the web using Tavily, its integration with the Strands SDK, and Amazon Bedrock AgentCore runtime and memory. We'll use a finance agent system as our example.
Amazon Bedrock AgentCore is a new service that serves as a production-ready toolkit to deploy and operate highly capable AI agents securely, at scale. It offers infrastructure purpose-built for dynamic agent workloads, powerful tools to enhance agents, and essential controls for real-world deployment. It encompasses a variety of features from a platform to host agents and MCP servers, a gateway for tools in AWS and third party, to a memory solution for agents as well as an identity management feature.
Overview
There are now quite a few ways to give AI Agents access to the web and allow them to perform web searches. One way is to build your own web scraper using Python modules like BeautifulSoup and http. Another way is to go the managed route, with AgentCore Browser , through which you can give full browser access to your multimodal models and allow them to perform actions and interacting with it using actions such as to "click" on a button, etc. AgentCore Browser is a game-changer when it comes to enabling AI Agents to peform complex automated tasks on the internet. This is somewhere in between, whereby Tavily provides a fully managed API to perform web searches as well as to parse content on web sites, among others. Moreover, it integrates seamlessly with the Strands framework so no custom code needs to be written to enable this.
There are also several multi-agent capabilities you can use out-of the box with strands, including swarms, where agents work collaboratively to solve a particular task with shared memory and state and one chooses to invoke another, graph or workflow, which allows for deterministic sequences of agent invocations for per-determined flows, and agent-as-a-tool. Agent-as-a-tool allows a single main orchestrator agent to invoke sub-agents as if they were a capability of the orchestrator agent itself, much like a manager delegating to its subordinates. The principal here is that several specialized agents (perhaps with their own foundation models), are able to work better together to accomplish a task than a single large model.
In this example, we have three agents:
- Market Researcher Agent: Uses the Tavily extension for web search and research. Writes a report highlighting key insights from the research.
- Finance Analyst Agent: Retrieves and analyzes financial metrics using the Yahoo Finance API (adapted from the Strands sample )
- Orchestrator Agent: Coordinates between specialized agents
Prerequisites
- AWS Account with appropriate permissions
- Tavily API key (get it here )
- Python 3.9+
- Docker installed
- AWS CLI configured
Walkthrough
Here, we will go through a process to develop the production-ready agentic system with web access.
Step 1: Set Up Dependencies
Create your
requirements.txt :strandsstrands-toolsyfinanceboto3bedrock-agentcore-starter-toolkitStep 2: Configure Tavily API Key
Store your Tavily API key securely in AWS Secrets Manager , then retrieve it and store it as an environment variable for the Strands-Tavily integration as follows:
# market_researcher.py
import boto3import json
secrets_client = boto3.client('secretsmanager', region_name="us-west-2")
def get_api_key(secret_id: str = 'financeassistant/tavily/apikey'): response = secrets_client.get_secret_value(SecretId=secret_id) secret_value = response['SecretString'] return json.loads(secret_value)
# Set environment variableos.environ['TAVILY_API_KEY'] = get_api_key()['key']Step 3: Create the Market Researcher Agent
The market researcher uses Tavily tools for web search capabilities:
# market_researcher.py
from strands import Agent, toolfrom strands.models import BedrockModelfrom strands_tools.tavily import tavily_search, tavily_extract, tavily_crawl
def get_market_researcher(memory_id: str, session_id: str = ''): model = BedrockModel(model_id="us.amazon.nova-pro-v1:0", region="us-west-2") researcher = Agent( model=model, system_prompt="You are a market researcher. Based on the query perform research on relevant cryptocurrencies, stocks or other investments. Provide a detailed report and analysis based on your research.", tools=[tavily_search, tavily_extract, tavily_crawl], state={'actor_id': 'market_researcher'} | ({'session_id': session_id} if session_id else {}) )
@tool def market_researcher(query: str) -> str: """ Handle market research queries and performing research on the web Args: query: Research query about stocks, crypto, or market trends Returns: Comprehensive research report """ return str(researcher(query)) return market_researcherWe will discuss about how to enable the memory and session-management later using what we have implemented here.
Step 4: Create the Finance Analyst Agent
This agent focuses on financial metrics using the Yahoo Finance API for real-time financial metrics:
# finance_analyst.py
from strands import Agent, toolimport yfinance as yf
@tooldef get_financial_metrics(ticker: str) -> Dict[str, Any]: """Fetches key financial metrics for a given stock ticker.""" stock = yf.Ticker(ticker) info = stock.info return { "status": "success", "data": { "symbol": ticker, "market_cap": info.get("marketCap", "N/A"), "pe_ratio": info.get("trailingPE", "N/A"), "dividend_yield": info.get("dividendYield", "N/A"), # ... other metrics } }
def get_finance_analyst(memory_id: str, session_id: str = ''): model = BedrockModel(model_id="us.amazon.nova-pro-v1:0", region="us-west-2") analyst = Agent( model=model, system_prompt="You are a financial analyst. Use the tools to analyze financial metrics and provide comprehensive reports.", tools=[get_financial_metrics], state={'actor_id': 'finance_analyst'} | ({'session_id': session_id} if session_id else {}) )
@tool def finance_analyst(query: str) -> str: """Analyzes financial metrics for companies or assets.""" return str(analyst(query)) return finance_analystStep 5: Create the Orchestrator Agent
The orchestrator coordinates between the two specialized agents, and creates a report:
# orchestrator.py
from strands import Agent, toolfrom strands.models import BedrockModelfrom finance_analyst import get_finance_analystfrom market_researcher import get_market_researcher
def get_orchestrator(memory_id: str, session_id: str = ''): model = BedrockModel(model_id="us.amazon.nova-pro-v1:0", region="us-west-2") # Get agent tools market_researcher = get_market_researcher(memory_id, session_id) finance_analyst = get_finance_analyst(memory_id, session_id) return Agent( model=model, system_prompt="You are a financial advisor. Use the market researcher for web-based research and the finance analyst for metrics analysis. Combine their reports into comprehensive investment advice.", tools=[market_researcher, finance_analyst], state={'actor_id': 'orchestrator'} | ({'session_id': session_id} if session_id else {}) )Step 6: Give the Agent Memory (Optional)
AgentCore, in addition to providing a runtime to run agents and MCP servers, also provides a memory capability that allows you to give short-term and long-term memory to our agents. Short-term memory is memory that generally persist for the duration of a session, normally to store chat interactions or the like. Long-term memory is a capability that extracts insights directly from the short term memory and stores it in a way that can be semantically searched. This is normally used for user preferences and similar use cases where you want to deliver a more personalized or coherent experience.
To create this memory we can follow the code from the AgentCore samples . Here, we set the
memory_id to pass into the orchestrator agent instantiation. Then we can add a hook to our agent to add memory to it . Hooks in Strands allow us to extend the agents functionality by tapping into its events. This can be useful for example, for monitoring purposes when you log events as needed. It is also is helpful to store memory as it is being created, as well as loading it on agent instantiation. Once we have the memory store created and integrated, we can import the memory ID into our entrypoint as another parameter, which we will go through now. Step 7: Create the Invocation Entrypoint
Now we will define a function that is to be called to get streaming responses from the agent, which is enabled through the asyncio usage in the Strands SDK:
# main.py
import asynciofrom bedrock_agentcore.runtime import BedrockAgentCoreAppfrom orchestrator import get_orchestrator
app = BedrockAgentCoreApp() # Instantiate the app
@app.entrypoint # Set the entrypoint where the main agent gets invokedasync def finance_advisor(payload, context): """ Invoke the agent with a payload """ user_input = payload.get("prompt") print("User input:", user_input)
orchestrator = get_orchestrator( memory_id=AGENTCORE_MEMORY_ID, session_id=context.session_id ) # Stream each chunk as it becomes available async for event in orchestrator.stream_async(user_input): if "data" in event: yield event["data"]
if __name__ == "__main__": app.run() # Run the app
Notice that to integrate it with AgentCore runtime, all that we need to do is import
BedrockAgentCoreApp class from the AgentCore SDK, instantiate the app, and then configure it to run as the AgentCore Endpoint is invoked. Furthermore, the session is automatically managed by the runtime, which simply passes the session ID through the context object when the endpoint is invoked. Now, we will deploy the agents to AgentCore runtime. Step 8: Deployment with the AgentCore SDK
Once we have our AWS credentials configured, deploying the agents to AgentCore can be automated by using the SDK:
# deploy.py
from bedrock_agentcore_starter_toolkit import Runtime
agentcore_runtime = Runtime()
response = agentcore_runtime.configure( entrypoint="main.py", auto_create_execution_role=True, auto_create_ecr=True, requirements_file="requirements.txt", region="us-west-2", agent_name="finance_advisor_agent") # Create the Dockerfile
launch_result = agentcore_runtime.launch() # Build and DeployThis will create the Dockerfile for the runtime and deploy it to AgentCore. Note the endpoint ARN:
# deploy.pyprint("Endpoint ARN:") # Print the AgentCore endpointprint(launch_result.agent_arn)Step 9: Invoke the Endpoint
Once the multi-agent system is deployed, you can then invoke the endpoint and stream the responses using the following class:
# streaming_invocation.py
import boto3import jsonimport uuidimport os
class FinanceAgentStreamer: def __init__(self): self.region = os.getenv('AWS_REGION', 'us-west-2') self.agent_arn = os.getenv('AGENT_ARN', 'arn:aws:bedrock-agentcore:AWS_REGION:ACCOUNT_ID:runtime/AGENT_NAME') self.client = boto3.client('bedrock-agentcore', region_name=self.region) def stream_response(self, prompt, session_id=None): """Generator that yields streaming response chunks""" if not session_id: session_id = str(uuid.uuid4()) response = self.client.invoke_agent_runtime( agentRuntimeArn=self.agent_arn, qualifier="DEFAULT", payload=json.dumps({"prompt": prompt}), runtimeSessionId=session_id ) if "text/event-stream" in response.get("contentType", ""): content = [] for line in response["response"].iter_lines(chunk_size=1): if line: line = line.decode("utf-8") if line.startswith("data: "): data = line[6:].replace('"', '').replace("\\n", "\n") content.append(data) yield "".join(content) else: # Handle non-streaming response try: events = [] for event in response.get("response", []): events.append(event) if events: yield json.loads(events[0].decode("utf-8")) except Exception as e: yield f"Error: {e}"
Then once this object is initialized with the right environment, the agent can be invoked by calling the
streamer.stream_response() method and passing in the prompt:# streaming_invocation.py
if __name__ == "__main__": prompt = "Recommend me a growth stock portfolio including the portfolio weights" session_id = "SESSION-1234" for partial_response in streamer.stream_response(prompt, session_id): print(partial_response)Best Practices
While this system is indeed production-capable, it is not yet production ready by itself. To get it production ready, the following needs to be ensured.
- Secret Management: Always use AWS Secrets Manager for API keys
- Error Handling: Implement robust error handling in tools
- Rate Limiting: Be mindful of API rate limits for both Tavily and financial data
- Caching: Consider caching frequently requested data
- Monitoring: Use AgentCore's observability features and integration with CloudWatch for production monitoring
Conclusion
This architecture provides a robust foundation for building production-ready AI agents with web search capabilities, demonstrating how to effectively combine specialized agents using the agent-as-a-tool pattern. We started by creating the agent-as-tools workflow with the Strands SDK, then implemented memory features with AgentCore Memory, before deploying the system to AgentCore runtime and invoking it with a streaming response.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article