You’re about to build something that didn’t exist two years ago. An AI trading agent. Not a bot that follows rules you hardcoded. Not a chatbot that pretends to understand markets. A genuine autonomous agent that reads natural language, thinks about what you’re asking, fetches real-time data, and executes trades—all because an LLM decided that’s what you wanted.
This matters because AI trading agents just executed over $44 billion in notional volume across prediction and DeFi markets in 2025, and their capabilities are improving roughly fourfold year-over-year. That’s not hype. That’s velocity. And the barrier to entry? Lower than you think.
This guide walks you through building a production-grade agent using OpenAI or Claude function calling, wired to Swap API—a free, unauthenticated endpoint that quotes token swaps across 46 EVM chains. No API keys. No paid tiers. No authentication theater. Just you, Python, and an LLM smart enough to know when to pull the trigger.
The Platform Shift Nobody’s Talking About
Function calling isn’t new. What’s new is that 93% of IT executives are now exploring agentic AI, and tool-use is the mechanism—the literal plumbing—that transforms a chatbot into an agent. This is analogous to the moment the web browser turned the internet into something non-technical people could use. Before that, you needed to understand TCP/IP and file transfers. After Netscape, you just clicked. Function calling is Netscape for AI.
Here’s what that means: Your agent won’t just respond to questions. It will autonomously decide when to fetch a swap quote, interpret the results, warn you about slippage, and hand you transaction data ready to sign. The LLM becomes a reasoning layer sitting on top of your APIs.
What You Need Before You Start
Keep this simple. Three things:
- Python 3.10+ with
requestsand eitheropenaioranthropiclibraries - A wallet address on any supported EVM chain (you don’t need the private key for quoting)
- An OpenAI or Anthropic API key
pip install openai requests web3 gets you 90% of the way there.
The Swap API itself is free. Completely. It’s unauthenticated and rate-limited to roughly 30 requests per minute per IP—more than enough for learning and small-scale production.
Defining Your Trading Tool
Function calling works by defining a schema that the LLM can “see.” It’s like handing the model a menu of what it’s allowed to do. Here’s the tool definition for swap quotes:
swap_tool = {
"type": "function",
"function": {
"name": "get_swap_quote",
"description": "Get a DEX swap quote with executable calldata",
"parameters": {
"type": "object",
"properties": {
"chain_id": {
"type": "integer",
"description": "EVM chain ID (1=Ethereum, 42161=Arbitrum, 8453=Base)"
},
"token_in": {
"type": "string",
"description": "Input token contract address"
},
"token_out": {
"type": "string",
"description": "Output token contract address"
},
"amount": {
"type": "string",
"description": "Amount in smallest unit (wei for ETH)"
},
"sender": {
"type": "string",
"description": "Wallet address that will execute the swap"
}
},
"required": ["chain_id", "token_in", "token_out", "amount", "sender"]
}
}
}
Notice the amount field. It’s not in dollars or human-readable units. 1 ETH is "1000000000000000000" (18 decimals). 100 USDC is "100000000" (6 decimals). Your agent needs to know token decimals to construct correct amounts—something we’ll handle in the system prompt.
Does This Actually Work? Test It First
Before you wire up the agent, verify the endpoint:
curl "https://api.swapapi.dev/v1/swap/42161?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xaf88d065e77c8cC2239327C5EDb3A432268e5831&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
That fetches a quote for 1 ETH → USDC on Arbitrum. The response includes tx.data (encoded calldata), tx.to (the router contract), and expectedAmountOut in raw units. This is everything you need to execute the trade on-chain.
Wiring Up the Agent Loop
Here’s where it all connects. The LLM receives user messages, decides whether to call the swap tool, processes the result, and responds in natural language.
import openai
import json
client = openai.OpenAI()
TOOLS = [swap_tool]
SYSTEM_PROMPT = """You are a DeFi trading assistant. You help users get swap quotes.
Common token addresses:
- ETH native: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
- USDC (Ethereum): 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
- USDC (Arbitrum): 0xaf88d065e77c8cC2239327C5EDb3A432268e5831
- USDC (Base): 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
- WETH (Arbitrum): 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1
- WETH (Base): 0x4200000000000000000000000000000000000006
Always confirm the quote details before suggesting execution.
Warn the user if price impact exceeds 5%."""
def get_swap_quote(chain_id, token_in, token_out, amount, sender):
url = f"https://api.swapapi.dev/v1/swap/{chain_id}"
params = {
"tokenIn": token_in,
"tokenOut": token_out,
"amount": amount,
"sender": sender,
}
resp = requests.get(url, params=params, timeout=15)
data = resp.json()
if not data.get("success"):
return {"error": data.get("error", {}).get("message", "Unknown error")}
status = data["data"]["status"]
if status == "NoRoute":
return {"status": "NoRoute", "message": "No swap route found"}
result = {
"status": status,
"token_in": data["data"]["tokenFrom"]["symbol"],
"token_out": data["data"]["tokenTo"]["symbol"],
"amount_in": data["data"]["amountIn"],
"expected_out": data["data"]["expectedAmountOut"],
"min_out": data["data"]["minAmountOut"],
"price_impact": data["data"]["priceImpact"],
"decimals_out": data["data"]["tokenTo"]["decimals"],
}
if status == "Partial":
result["warning"] = "Only a partial fill is available"
return result
def run_agent(user_message, wallet_address):
messages = [{"role": "user", "content": user_message}]
while True:
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
tools=TOOLS,
system=SYSTEM_PROMPT
)
if response.stop_reason == "end_turn":
return response.choices[0].message.content
if response.stop_reason == "tool_calls":
tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
# Add sender if not provided
if "sender" not in args:
args["sender"] = wallet_address
result = get_swap_quote(**args)
messages.append({"role": "assistant", "content": response.choices[0].message.content})
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": json.dumps(result)
})
That’s your agent. You call run_agent("Swap 1 ETH for USDC on Arbitrum", your_wallet_address) and it handles the rest. The LLM decides it needs a quote, calls the function, interprets the result, and returns human-readable output.
Why This Matters for You (Beyond the Hype)
Here’s what the crypto media won’t tell you: Building agents like this used to require hiring a team. Six months ago, you’d need to manually build Flask endpoints, deploy to a server, handle authentication, orchestrate API calls, and write custom retry logic. Today? It’s a Python script and a function definition.
The real opportunity isn’t in copying what others have built. It’s in understanding that function calling is now the primitives layer for autonomous systems. Once you grok this pattern—define tools, let the LLM choose when to use them, process the results—you can chain together any API. Market data. On-chain analytics. Governance dashboards. Liquidation alerts. The architecture scales.
And because Swap API is free and unauthenticated, you can experiment without worrying about bills or rate limits hitting you in production.
What Happens Next?
Once your agent is working locally, here’s the play: Deploy it as a serverless function (AWS Lambda, Vercel, Railway). Add persistent memory so the agent remembers your trading preferences. Integrate with a wallet signer so quotes can become actual transactions. Hook it into Discord or Telegram so you can request quotes from your phone.
That’s not science fiction. That’s Tuesday in the open-source DeFi ecosystem.
“Function calling is the recommended pattern for giving models structured access to external APIs,” according to OpenAI’s agent documentation—which means every major AI vendor is betting on this architecture.
🧬 Related Insights
- Read more: Why Open Source Contributions Aren’t Charity—They’re a $2.6 Trillion Business Move
- Read more: I Built a Research Agent That Queries 10 Sources in 45 Seconds—Here’s Why Your Sequential Approach Is Dead
Frequently Asked Questions
Can I use this agent without paying for an API key? Yes. Swap API is completely free and unauthenticated. You’ll need an OpenAI or Anthropic key, but those have free trials ($5-$18 in free credits). Your first hundred trades cost zero.
Will this actually execute swaps, or just quote them? It quotes them. Execution requires signing the transaction with your private key—which you control separately. The agent returns the calldata and contract address; you choose whether to broadcast it.
What chains does this work on?
Any EVM chain. Ethereum, Arbitrum, Base, Optimism, Polygon, Avalanche, and 40+ others. The chain_id parameter determines which network you’re quoting on.
How fast is it? Quotes return in 1-3 seconds on average. The bottleneck is the LLM thinking time, not the API. OpenAI’s function calling adds 500-1000ms per round-trip.