✦ Agent Code

AI Agent Code Library

Copy-ready starter code to create AI agents with the most popular SDKs and frameworks. Paste, add your API key, run.

πŸ’‘ Set your provider key first (e.g. export ANTHROPIC_API_KEY=… or OPENAI_API_KEY). Model names and SDK versions change often β€” check each project's docs for the latest.

Raw tool-use loop β€” Claude API (Python)

The core pattern behind every agent: the model asks for a tool, your code runs it, the result goes back, repeat until done.

pip install anthropic Β· Docs β†—

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY

def get_weather(city: str) -> str:
    return f"It's 68Β°F and sunny in {city}."   # call a real API here

tools = [{
    "name": "get_weather",
    "description": "Get the current weather for a city.",
    "input_schema": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"],
    },
}]

messages = [{"role": "user", "content": "Should I bring a jacket in Monterey today?"}]

while True:
    resp = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=1024,
        tools=tools,
        messages=messages,
    )
    messages.append({"role": "assistant", "content": resp.content})

    if resp.stop_reason != "tool_use":
        print("".join(b.text for b in resp.content if b.type == "text"))
        break

    results = []
    for block in resp.content:
        if block.type == "tool_use":
            output = get_weather(**block.input)
            results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
    messages.append({"role": "user", "content": results})

OpenAI Agents SDK (Python)

Define an agent with instructions and function tools; the Runner handles the loop.

pip install openai-agents Β· Docs β†—

from agents import Agent, Runner, function_tool

@function_tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"It's 68Β°F and sunny in {city}."

agent = Agent(
    name="Weather helper",
    instructions="Answer briefly and practically.",
    tools=[get_weather],
)

result = Runner.run_sync(agent, "Should I bring a jacket in Monterey today?")
print(result.final_output)

Claude Agent SDK (Python)

The same harness that powers Claude Code β€” built-in file, shell and web tools, ready to use.

pip install claude-agent-sdk Β· Docs β†—

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        system_prompt="You are a careful code reviewer.",
        allowed_tools=["Read", "Grep", "Glob"],
    )
    async for message in query(prompt="Review the files in ./src for bugs.", options=options):
        print(message)

asyncio.run(main())

Multi-agent team β€” CrewAI (Python)

Give each agent a role and goal, assign tasks, and let the crew work in sequence.

pip install crewai Β· Docs β†—

from crewai import Agent, Task, Crew

researcher = Agent(
    role="Market Researcher",
    goal="Find the top AI agent platforms for small businesses",
    backstory="You research software markets and cite your sources.",
)
writer = Agent(
    role="Content Writer",
    goal="Turn research into a clear, friendly blog post",
    backstory="You write plain-English guides for busy owners.",
)

research = Task(
    description="List 5 AI agent platforms for small businesses with pros and cons.",
    expected_output="A bullet list of 5 platforms with pros/cons.",
    agent=researcher,
)
post = Task(
    description="Write a 400-word blog post from the research.",
    expected_output="A 400-word blog post in markdown.",
    agent=writer,
)

crew = Crew(agents=[researcher, writer], tasks=[research, post])
print(crew.kickoff())

LangChain agent (Python)

A prebuilt tool-calling agent in a few lines; swap in any supported model.

pip install langchain langchain-anthropic Β· Docs β†—

from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"It's 68Β°F and sunny in {city}."

agent = create_agent(
    model="anthropic:claude-sonnet-5-5",
    tools=[get_weather],
    system_prompt="You are a helpful assistant.",
)

result = agent.invoke({"messages": [{"role": "user", "content": "Weather in Monterey?"}]})
print(result["messages"][-1].content)

Build an MCP server (Python)

Expose your own tools to any MCP-compatible agent β€” Claude, ChatGPT, Cursor and more.

pip install "mcp[cli]" Β· Docs β†—

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("listings")

@mcp.tool()
def search_listings(city: str, max_price: int) -> list[dict]:
    """Search property listings in a city under a max price."""
    # Replace with a real database or API call
    return [{"address": "123 Ocean Ave", "city": city, "price": max_price - 50000}]

if __name__ == "__main__":
    mcp.run()   # stdio transport by default

Tool-calling agent β€” Vercel AI SDK (TypeScript)

For web developers: a multi-step agent with typed tools in Node or Next.js.

npm i ai @ai-sdk/anthropic zod Β· Docs β†—

import { generateText, tool, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { z } from "zod";

const { text } = await generateText({
  model: anthropic("claude-sonnet-5-5"),
  stopWhen: stepCountIs(5),
  tools: {
    getWeather: tool({
      description: "Get the current weather for a city",
      inputSchema: z.object({ city: z.string() }),
      execute: async ({ city }) => `It's 68Β°F and sunny in ${city}.`,
    }),
  },
  prompt: "Should I bring a jacket in Monterey today?",
});

console.log(text);
✦ Roadmap

How to Build an AI Agent

Define the job

One clear goal, the inputs it gets, and what β€œdone” looks like.

Pick model + framework

Start with a vendor SDK; reach for LangGraph or CrewAI when you need complex flows or teams.

Write tools

Small functions with clear names, descriptions and typed inputs β€” or plug in MCP servers.

Add knowledge

Retrieval from a vector DB or a memory layer like Mem0 for long-term context.

Guardrails & evals

Limit permissions, require approval for risky actions, trace with Langfuse or LangSmith.

Deploy

Run in a sandbox (E2B), a serverless function, or a managed platform like Bedrock AgentCore.

Browse every tool mentioned here in Build Agents β†’