页面简介
Learn how to build production-ready AI agents on Ray Serve using MCP and A2A, with independently autoscaling LLMs, tools, and agents for scalable single- and multi-agent systems.
正文摘录
HomeBlogBlog Detail AI agents on Ray Serve: Single to multi-agent architectureBy Kunling Geng and Aydin Abiar | May 7, 2026Most agent frameworks solve orchestration — prompt chaining, tool calling, memory — but leave infrastructure management unresolved. Transitioning beyond a single-process prototype immediately exposes three problems: the GPU-heavy LLM and the lightweight agent logic cannot scale independently, every new tool requires redeploying the agent, and composing agents means tight coupling through shared imports. The result is fragile monoliths that break under production traffic.That challenge sits one layer below what we covered in our April 22 announcement of Anyscale Agent Skills. While Agent Skills focuses on packaging and reusing agent capabilities, this post focuses on the production infrastructure needed to run them reliably at scale.This post describes a microservices approach to AI agents built on Ray Serve, MCP (Model Context Protocol), and the A2A (Agent-to-Agent) protocol. It details two reference implementations — a single tool-using agent and a multi-agent system — where each component (LLM, tools, agents) runs as an independently autoscaling Ray Serve application.LinkWhy Agent Infrastructure Is Hard TodayBuilding a prototype agent takes minutes. Deploying it to production means confronting a layer of infrastructure complexity underneath — compute orchestration, state management, observability, fault tolerance, security, and LLM-specific concerns like rate limiting and token budgets — that cuts across every component. Most of these concerns are table stakes for any distributed system, but three bottlenecks are unique to how agents are built today:Scaling is all-or-nothing. In a monolithic deployment, GPU-intensive LLM inference and lightweight CPU orchestration scale as a single unit. During a traffic spike, you either over-provision expensive L4 GPUs just to handle simple agent logic (driving up costs) or starve the LLM of compute. In multi-agent systems this compounds: three agents sharing one process means a slow research query blocks weather responses.Tool integration is tightly coupled. Hard-coding tool functions into the agent means every new tool requires code changes and redeployment. When the Weather API adds a get_air_quality endpoint, you want the agent to discover it at runtime — not wait for a release cycle.Agent composition is fragile. When one agent delegates to another via direct function imports, any change to the downstream agent's interface breaks the upstream caller. There's no standard for agent discovery, versioning, or traceable inter-agent communication.LinkWhat Production Agent Infrastructure RequiresThese three bottlenecks are symptoms of a broader gap: agent frameworks handle orchestration, but production deployments demand a full infrastructure layer. The table below maps out the core requirements — spanning compute, operations, security, and connectivity — that any production agent platform must address.RequirementDescriptionWhy It MattersFramework IndependenceSupport for diverse LLM frameworks (LangChain, LlamaIndex, CrewAI, AutoGPT)Prevents vendor lock-in; allows teams to use the best tool for the jobDeveloper VelocityStreamlined CI/CD pipelines for rapid iteration, testing, and deploymentReduces time-to-market for complex agentic workflowsElastic ScalabilityDynamic resource allocation based on real-time traffic and compute demandsHandles bursty agent workloads without over-provisioning costsResilience & AvailabilitySelf-healing systems that recover from hardware or framework-level failuresEnsures agents remain active and responsive 24/7 in productionSecure Access ControlCentralized IAM for managing deployment permissions and agent interactionCritical for enterprise compliance and data securityFull-Stack ObservabilityIntegrated telemetry including distributed logs, traces, and performance metricsEnables rapid debugging of complex, multi-step agent reasoning loopsMemory & PersistenceManaged storage for short-term (contextual) and long-term (episodic) memoryAllows agents to maintain state across sessions and complex tasksGranular ConnectivityPolicy-based network access to internal and external environments (VPC/Internet)Securely connects agents to enterprise data and external toolsAl Agent ArchitectureThe architectures that follow address several of these requirements directly — elastic scalability through independent autoscaling, framework independence via OpenAI-compatible APIs, observability through Ray Dashboard metrics, and resilience through fault-isolated services — while the Anyscale platform completes the picture with secure access control, managed connectivity, and production-grade availability.LinkArchitecture 1: Single Agent with MCP ToolsThe single-agent deployment (available as the langchain-agent-ray-serve template) consists of three Ray Serve applications.The architecture splits every component into its own Ray Serve application with independent scaling, routing, and fault domains:ComponentRoleInterfaceResourcesScalingLLM ServiceQwen3-4B-Instruct-2507-FP8 inferenceOpenAI-compatible API1× L4 GPU (24 GB)Request-based autoscalingMCP Tool ServerWeather APIMCP streamable HTTP0.2 CPU each1–20 replicas, target 5 in-flight req/replicaAgent ServiceLangChain orchestrationSSE streaming1 CPU eachRequest-based autoscalingLLM Tool Calling Workflow with Agent, MCP, and Weather Service IntegrationLinkLLM as a ServiceThe LLM runs as a dedicated Ray Serve application using Ray Serve LLM's build_openai_app, which wraps vLLM behind an OpenAI-compatible API:from ray.serve.llm import LLMConfig, build_openai_app llm_config = LLMConfig( model_loading_config=dict( model_id="Qwen/Qwen3-4B-Instruct-2507-FP8", model_source="Qwen/Qwen3-4B-Instruct-2507-FP8", ), accelerator_type="L4", engine_kwargs=dict( max_model_len=65536, trust_remote_code=True, gpu_memory_utilization=0.9, enable_auto_tool_choice=True, tool_call_parser="hermes", ), ) app = build_openai_app({"llm_configs": [llm_config]}) Two flags are critical for agent workloads: enable_auto_tool_choice=True lets the model decide autonomously when to invoke tools, and tool_call_parser="hermes" parses Qwen's native function-calling format (Qwen3 Instruct emits Hermes-style tool calls). The 64K context window (max_model_len=65536) provides headroom for multi-turn conversations with several tool-call rounds.LinkTools as MCP ServersInstead of hard-coding tools into the agent, we expose them as MCP servers — the open standard for runtime tool discovery. Each tool server is a stateless, horizontally scalable Ray Serve deployment:from mcp.server.fastmcp import FastMCP from ray import serve mcp = FastMCP("weather", stateless_http=True) @mcp.tool() async def get_forecast(latitude: float, longitude: float) -> str: """Fetch a multi-period weather forecast for given coordinates.""" # Calls the National Weather Service API ... fastapi_app = mcp.streamable_http_app() @serve.deployment( autoscaling_config={ "min_replicas": 1, "max_replicas": 20, "target_ongoing_requests": 5, }, ray_actor_options={"num_cpus": 0.2}, ) @serve.ingress(fastapi_app) class WeatherMCP: passThe autoscaling_config scales the deployment between 1 and 20 replicas, targeting 5 concurrent in-flight requests per replica. Fractional CPU resources (num_cpus=0.2) let the scheduler pack many MCP replicas onto a single node, since the work is I/O-bound rather than CPU-bound.LinkThe Agent: LangChain + Dynamic Tool DiscoveryThe agent uses LangChain v1's create_agent with tools discovered at runtime from the MCP server via MultiServerMCPClient:from langchain.agents import create_agent from langchain_mcp_adapters.client import MultiServerMCPClient from langgraph.checkpoint.memory import MemorySaver async def build_agent(): mcp_client = MultiServerMCPClient({ "weather": { "url": urljoin(WEATHER_MCP_BASE_URL, "mcp"), "transport": "streamable_http", } }) tools = await mcp_client.get_tools() memory = MemorySaver() return create_agent(llm, tools, system_prompt=PROMPT, checkpointer=memory)Note: This example uses LangGraph's in-memory MemorySaver for simplicity. A production deployment should swap it for a persistent LangGraph checkpointer such as PostgresSaver or SqliteSaver (or a Redis-backed equivalent) so conversation state survives Ray Serve replica restarts.Add a new get_air_quality tool to the MCP server and the agent picks it up the next time build_agent() runs (e.g., on replica startup) — no agent code changes. The agent itself is wrapped in a Ray Serve deployment with a /chat SSE streaming endpoint.LinkArchitecture 2: Multi-Agent System with A2A ProtocolThe multi-agent system (available as the multi_agent_a2a template) extends the single-agent pattern with three specialized agents communicating through the A2A protocol:Weather Agent: Answers weather questions via Weather MCP toolsResearch Agent: Performs web research via Web Search MCP tools (brave_search, fetch_url)Travel Agent: Orchestrates both agents through A2A to create weather-aware travel plansMulti-Agent A2A Architecture with Ray Serve & AnyscaleLinkWhy A2A Instead of Direct ImportsWhen the Travel Agent needs weather data, it could import the Weather Agent directly. But direct imports create tight coupling. A2A solves this with HTTP boundaries and standardized discovery:AspectDirect IntegrationA2A ProtocolCouplingTight — shared importsLoose — HTTP + JSON boundariesDiscoveryHard-coded endpointsDynamic via /.well-known/agent-card.jsonVersioningCode changesProtocol-level, backward-compatibleDebuggingComplex call stacksTraceable per-task with unique task IDsFailure handlingCascading failuresIndependent — partial results possibleEach A2A-enabled agent advertises its capabilities through an AgentCard (served at GET /.well-known/agent-card.json) and accepts work through the REST transport's POST /v1/message:send endpoint (the JSON-RPC transport exposes the equivalent message/send method on the root endpoint). The Tr