Global API
← Back to Blog

How to Build AI Agents with DeepSeek API: A Practical Guide

2026-05-22 — by Global API Team

How to Build AI Agents with DeepSeek API: A Practical Guide
deepseekai-agentsfunction-callingtutorialllmtutorial

How to Build AI Agents with DeepSeek API: A Practical Guide

Large Language Models have evolved from simple text completions into reasoning engines that can plan, use tools, and take autonomous actions. This shift—called the agentic era—is changing how developers build AI-powered applications. DeepSeek, with its powerful deepseek-chat and deepseek-reasoner models, provides one of the most cost-effective foundations for building production AI agents.

In this guide, you'll learn:

  • What AI agents are and why they matter
  • How function calling (tool use) works with DeepSeek
  • How to build a simple agent loop in Python and JavaScript
  • Real-world patterns for multi-step task execution
  • Cost optimization using Global API's GA Fusion routing

All code examples are production-ready and can be copied directly. Let's dive in.


What Is an AI Agent?

An AI agent is a system where an LLM doesn't just answer a single prompt—it maintains a state, plans a sequence of actions, calls external tools (APIs, databases, calculators), and iterates until a goal is reached.

Think of it this way:

| Traditional Chat | AI Agent | |-----------------|----------| | Single prompt → single response | Goal → plan → execute tools → evaluate → respond | | Stateless | Stateful (maintains conversation context) | | No external actions | Can call APIs, read files, search web | | One-shot answer | Multi-step reasoning with self-correction |

A concrete example: instead of asking "What's the weather in Beijing?" and getting a text response, an agent would:

  1. Recognize it needs weather data
  2. Call a weather API tool
  3. Receive the raw data
  4. Formulate a natural-language answer

DeepSeek's models support this pattern natively through function calling (also called tool use), which we'll explore in detail.


Setting Up Your DeepSeek API Client

Before building agents, you need a working DeepSeek API client. Get your API key from Global API — keys are 32-character hexadecimal strings with no prefix.

Python Setup

pip install openai httpx
# build-ai-agents-deepseek-api/python/agent_client.py
from openai import OpenAI

# Initialize client pointing to Global API proxy
client = OpenAI(
    api_key="YOUR_DEEPSEEK_API_KEY",  # 32-char hex string
    base_url="https://global-apis.com/v1"
)

def chat(messages: list[dict], model: str = "deepseek-chat") -> str:
    """Send a chat request to DeepSeek via Global API."""
    response = client.chat.completions.create(
        model=model,
        messages=messages,
        temperature=0.7,
        max_tokens=2048
    )
    return response.choices[0].message.content

# Test your connection
messages = [{"role": "user", "content": "Say hello in one sentence."}]
response = chat(messages)
print(response)

JavaScript/Node.js Setup

npm install openai
// build-ai-agents-deepseek-api/javascript/agent_client.js
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_DEEPSEEK_API_KEY', // 32-char hex string
  baseURL: 'https://global-apis.com/v1'
});

async function chat(messages, model = 'deepseek-chat') {
  const response = await client.chat.completions.create({
    model,
    messages,
    temperature: 0.7,
    max_tokens: 2048
  });
  return response.choices[0].message.content;
}

// Test your connection
const messages = [{ role: 'user', content: 'Say hello in one sentence.' }];
const response = await chat(messages);
console.log(response);

Function Calling: The Foundation of AI Agents

Function calling (or tool calling) is what makes agents possible. Instead of returning plain text, the model can output a structured JSON object requesting a specific function call. Your application executes the function and feeds the result back to the model.

How Function Calling Works

User: "What's the current price of Bitcoin?"
        │
        ▌
┌─────────────────┐
│  DeepSeek LLM   │
│  (deepseek-chat)│
└────────┬────────┘
         │ Decides it needs real-time data
         │ Outputs: { "tool": "get_crypto_price", "args": { "symbol": "BTC" } }
         ▌
┌─────────────────┐
│  Your Backend   │
│  (executes tool)│
└────────┬────────┘
         │ Returns: { "price": 67432.50, "currency": "USD" }
         ▌
┌─────────────────┐
│  DeepSeek LLM   │
└────────┬────────┘
         │ Formats natural-language response
         ▌
User: "Bitcoin is currently trading at $67,432.50 USD."

Defining Tools for DeepSeek

Tools are defined in the request payload using a schema. Here's a complete example:

# build-ai-agents-deepseek-api/python/function_calling.py
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_DEEPSEEK_API_KEY",
    base_url="https://global-apis.com/v1"
)

# Define the tools available to the agent
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_crypto_price",
            "description": "Get the current price of a cryptocurrency in USD",
            "parameters": {
                "type": "object",
                "properties": {
                    "symbol": {
                        "type": "string",
                        "description": "Crypto symbol (e.g., BTC, ETH)"
                    }
                },
                "required": ["symbol"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a city",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name"}
                },
                "required": ["city"]
            }
        }
    }
]

# Simulated tool implementations
def get_crypto_price(symbol: str) -> dict:
    """Simulated crypto price lookup."""
    prices = {"BTC": 67432.50, "ETH": 3521.20, "SOL": 142.80}
    return {"symbol": symbol, "price": prices.get(symbol.upper(), 0), "currency": "USD"}

def get_weather(city: str) -> dict:
    """Simulated weather lookup."""
    return {"city": city, "temp_c": 22, "condition": "Partly Cloudy"}

# Tool registry
TOOL_REGISTRY = {
    "get_crypto_price": get_crypto_price,
    "get_weather": get_weather
}

def run_agent(user_message: str, model: str = "deepseek-chat") -> str:
    """Run a single-step agent with function calling."""
    messages = [{"role": "user", "content": user_message}]

    response = client.chat.completions.create(
        model=model,
        messages=messages,
        tools=tools,
        tool_choice="auto"
    )

    response_message = response.choices[0].message

    # Check if the model wants to call a tool
    if response_message.tool_calls:
        tool_call = response_message.tool_calls[0]
        tool_name = tool_call.function.name
        tool_args = eval(tool_call.function.arguments)  # Parse JSON arguments

        print(f"[Agent] Calling tool: {tool_name}({tool_args})")

        # Execute the tool
        result = TOOL_REGISTRY[tool_name](**tool_args)

        # Feed result back to the model
        messages.append(response_message)
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": str(result)
        })

        # Get final response
        final_response = client.chat.completions.create(
            model=model,
            messages=messages
        )
        return final_response.choices[0].message.content

    return response_message.content

# Test it
result = run_agent("What's the current price of Bitcoin?")
print(result)
// build-ai-agents-deepseek-api/javascript/function_calling.js
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_DEEPSEEK_API_KEY',
  baseURL: 'https://global-apis.com/v1'
});

const tools = [
  {
    type: 'function',
    function: {
      name: 'get_crypto_price',
      description: 'Get the current price of a cryptocurrency in USD',
      parameters: {
        type: 'object',
        properties: {
          symbol: { type: 'string', description: 'Crypto symbol (BTC, ETH, SOL)' }
        },
        required: ['symbol']
      }
    }
  },
  {
    type: 'function',
    function: {
      name: 'get_weather',
      description: 'Get current weather for a city',
      parameters: {
        type: 'object',
        properties: {
          city: { type: 'string', description: 'City name' }
        },
        required: ['city']
      }
    }
  }
];

const TOOL_REGISTRY = {
  get_crypto_price: ({ symbol }) => {
    const prices = { BTC: 67432.50, ETH: 3521.20, SOL: 142.80 };
    return { symbol, price: prices[symbol.toUpperCase()] || 0, currency: 'USD' };
  },
  get_weather: ({ city }) => ({ city, temp_c: 22, condition: 'Partly Cloudy' })
};

async function runAgent(userMessage, model = 'deepseek-chat') {
  const messages = [{ role: 'user', content: userMessage }];

  const response = await client.chat.completions.create({
    model,
    messages,
    tools,
    tool_choice: 'auto'
  });

  const responseMessage = response.choices[0].message;

  if (responseMessage.tool_calls) {
    const toolCall = responseMessage.tool_calls[0];
    const toolName = toolCall.function.name;
    const toolArgs = JSON.parse(toolCall.function.arguments);

    console.log(`[Agent] Calling tool: ${toolName}(${JSON.stringify(toolArgs)})`);

    const result = TOOL_REGISTRY[toolName](toolArgs);

    messages.push(responseMessage);
    messages.push({
      role: 'tool',
      tool_call_id: toolCall.id,
      content: JSON.stringify(result)
    });

    const finalResponse = await client.chat.completions.create({
      model,
      messages
    });
    return finalResponse.choices[0].message.content;
  }

  return responseMessage.content;
}

// Test it
const result = await runAgent("What's the current price of Bitcoin?");
console.log(result);

Building a Multi-Step Agent Loop

Single-step function calling is powerful, but true agents need a loop that can:

  1. Plan the next action
  2. Execute a tool
  3. Evaluate the result
  4. Decide if more steps are needed or the task is complete

Here's a complete multi-step agent implementation:

# build-ai-agents-deepseek-api/python/multi_step_agent.py
from openai import OpenAI
import json

client = OpenAI(
    api_key="YOUR_DEEPSEEK_API_KEY",
    base_url="https://global-apis.com/v1"
)

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "search_database",
            "description": "Search a database for records matching a query",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "table": {"type": "string"}
                },
                "required": ["query", "table"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "send_email",
            "description": "Send an email to a recipient",
            "parameters": {
                "type": "object",
                "properties": {
                    "to": {"type": "string"},
                    "subject": {"type": "string"},
                    "body": {"type": "string"}
                },
                "required": ["to", "subject", "body"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "Perform a mathematical calculation",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {"type": "string", "description": "Math expression (e.g., '150 * 0.15')"}
                },
                "required": ["expression"]
            }
        }
    }
]

TOOL_REGISTRY = {
    "search_database": lambda q, table: {"found": 3, "records": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"}]},
    "send_email": lambda to, subject, body: {"status": "sent", "to": to},
    "calculate": lambda expression: {"result": eval(expression)}
}

MAX_ITERATIONS = 10

def run_agent_loop(task: str, model: str = "deepseek-chat") -> str:
    """
    Run an agent loop that can take multiple steps to complete a task.
    The model decides which tools to call until it has enough information.
    """
    messages = [
        {
            "role": "system",
            "content": """You are a helpful research assistant agent.
You have access to tools. When you need information, call the appropriate tool.
When you have completed the task, provide a clear summary of what you found or did.
Be concise but thorough."""
        },
        {"role": "user", "content": task}
    ]

    iterations = 0

    while iterations < MAX_ITERATIONS:
        iterations += 1
        print(f"\n--- Iteration {iterations} ---")

        response = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=TOOLS,
            tool_choice="auto"
        )

        response_message = response.choices[0].message
        print(f"[Model] {response_message.content[:200] if response_message.content else '(no text)'}")

        if not response_message.tool_calls:
            # No more tools needed, we're done
            return response_message.content

        # Process each tool call
        for tool_call in response_message.tool_calls:
            tool_name = tool_call.function.name
            tool_args = json.loads(tool_call.function.arguments)

            print(f"[Agent] Calling: {tool_name}({tool_args})")

            try:
                result = TOOL_REGISTRY[tool_name](**tool_args)
                print(f"[Agent] Result: {result}")

                messages.append(response_message)
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": json.dumps(result)
                })
            except Exception as e:
                messages.append(response_message)
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": json.dumps({"error": str(e)})
                })

    return "Agent reached maximum iterations without completing the task."

# Test the multi-step agent
task = "Find users in the database, calculate 15% of 150, and send an email to alice@example.com with the results."
result = run_agent_loop(task)
print(f"\n[Final Response]\n{result}")
// build-ai-agents-deepseek-api/javascript/multi_step_agent.js
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'YOUR_DEEPSEEK_API_KEY',
  baseURL: 'https://global-apis.com/v1'
});

const TOOLS = [
  {
    type: 'function',
    function: {
      name: 'search_database',
      description: 'Search a database for records matching a query',
      parameters: {
        type: 'object',
        properties: {
          query: { type: 'string' },
          table: { type: 'string' }
        },
        required: ['query', 'table']
      }
    }
  },
  {
    type: 'function',
    function: {
      name: 'send_email',
      description: 'Send an email to a recipient',
      parameters: {
        type: 'object',
        properties: {
          to: { type: 'string' },
          subject: { type: 'string' },
          body: { type: 'string' }
        },
        required: ['to', 'subject', 'body']
      }
    }
  },
  {
    type: 'function',
    function: {
      name: 'calculate',
      description: 'Perform a mathematical calculation',
      parameters: {
        type: 'object',
        properties: {
          expression: { type: 'string', description: "Math expression (e.g., '150 * 0.15')" }
        },
        required: ['expression']
      }
    }
  }
];

const TOOL_REGISTRY = {
  search_database: ({ query, table }) => ({ found: 3, records: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }] }),
  send_email: ({ to, subject, body }) => ({ status: 'sent', to }),
  // WARNING: eval is used here only for demonstration — use a safe math parser in production
  calculate: ({ expression }) => ({ result: eval(expression) })
};

const MAX_ITERATIONS = 10;

async function runAgentLoop(task, model = 'deepseek-chat') {
  const messages = [
    {
      role: 'system',
      content: `You are a helpful research assistant agent.
You have access to tools. When you need information, call the appropriate tool.
When you have completed the task, provide a clear summary.
Be concise but thorough.`
    },
    { role: 'user', content: task }
  ];

  for (let iterations = 0; iterations < MAX_ITERATIONS; iterations++) {
    console.log(`\n--- Iteration ${iterations + 1} ---`);

    const response = await client.chat.completions.create({
      model,
      messages,
      tools: TOOLS,
      tool_choice: 'auto'
    });

    const responseMessage = response.choices[0].message;
    console.log(`[Model] ${(responseMessage.content || '(no text)').slice(0, 200)}`);

    if (!responseMessage.tool_calls) {
      return responseMessage.content;
    }

    for (const toolCall of responseMessage.tool_calls) {
      const toolName = toolCall.function.name;
      const toolArgs = JSON.parse(toolCall.function.arguments);

      console.log(`[Agent] Calling: ${toolName}(${JSON.stringify(toolArgs)})`);

      const result = TOOL_REGISTRY[toolName](toolArgs);
      console.log(`[Agent] Result: ${JSON.stringify(result)}`);

      messages.push(responseMessage);
      messages.push({
        role: 'tool',
        tool_call_id: toolCall.id,
        content: JSON.stringify(result)
      });
    }
  }

  return 'Agent reached maximum iterations without completing the task.';
}

// Test
const task = 'Find users in the database, calculate 15% of 150, and send an email to alice@example.com with the results.';
const result = await runAgentLoop(task);
console.log(`\n[Final Response]\n${result}`);

Using deepseek-reasoner for Complex Agentic Tasks

For tasks that require deep multi-step reasoning—like solving multi-hop questions, debugging complex code, or planning a sequence of actions—the deepseek-reasoner model significantly outperforms deepseek-chat.

The key difference: deepseek-reasoner uses extended chain-of-thought reasoning and produces better tool-calling decisions in complex scenarios.

# build-ai-agents-deepseek-api/python/reasoner_agent.py
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_DEEPSEEK_API_KEY",
    base_url="https://global-apis.com/v1"
)

# Use deepseek-reasoner for complex agentic tasks
COMPLEX_TASK = """A user asks: 'I want to plan a 7-day trip to Tokyo. My budget is $2000 USD.
I like anime, food, and nature. Can you help me plan it day by day and estimate the total cost?'

Research: Search for average costs of activities in Tokyo, then plan each day."""

response = client.chat.completions.create(
    model="deepseek-reasoner",  # Use reasoner for complex planning
    messages=[{"role": "user", "content": COMPLEX_TASK}],
    tools=TOOLS,  # Same tools as before
    tool_choice="auto"
)

print("deepseek-reasoner response:")
print(response.choices[0].message.content)

When to use each model:

| Model | Best For | advertiseUsdPerM (Input) | |-------|----------|-------------------------| | deepseek-chat | Simple Q&A, single tool calls, high-volume tasks | $0.25 | | deepseek-reasoner | Complex planning, multi-step reasoning, debugging | $2.50 |

For simple, high-volume agent tasks (e.g., chatbots answering FAQs), deepseek-chat is the most cost-effective choice. For mission-critical agents that need to reason through complex decisions, deepseek-reasoner delivers significantly better results at a higher per-token cost.


Cost Optimization with GA Fusion Routing

Running agents at scale can get expensive. Global API's GA Fusion routing intelligently selects the best model for each request, balancing quality and cost:

| GA Fusion Tier | Credit Multiplier | Best For | |---------------|-------------------|----------| | ga-economy | 0.5x | Simple, high-volume agent tasks | | ga-standard | 1.0x | Balanced general-purpose agents | | ga-express | 1.5x | Low-latency, high-reliability production agents |

Using GA Fusion is simple — just change the model name:

# Cost-optimized agent using GA Fusion
def run_cost_optimized_agent(messages, complexity: str = "standard"):
    """Route to appropriate tier based on task complexity."""
    model_map = {
        "simple": "ga-economy",
        "standard": "ga-standard",
        "complex": "ga-express"
    }
    model = model_map.get(complexity, "ga-standard")

    response = client.chat.completions.create(
        model=model,
        messages=messages,
        tools=TOOLS
    )
    return response.choices[0].message.content

For a typical agent workload with 1,000 requests of mixed complexity:

| Strategy | Estimated Monthly Cost | |----------|------------------------| | All deepseek-reasoner | ~$150–200 | | GA Fusion (auto-routing) | ~$60–90 | | All deepseek-chat | ~$15–25 (but lower quality on complex tasks) |

GA Fusion gives you the best of both worlds: premium reasoning when needed, and economy pricing for simple tasks—all transparently managed.


Real-World Agent Patterns

Here are three production-ready patterns you can implement today:

Pattern 1: Research Agent

A research agent that searches multiple sources, synthesizes findings, and produces a report:

# build-ai-agents-deepseek-api/python/research_agent.py
RESEARCHER_PROMPT = """You are a research agent. Your job:
1. Search for information on the given topic
2. Compile key findings
3. Provide a structured summary with sources

Topic: {topic}
"""

def research_agent(topic: str) -> str:
    messages = [
        {"role": "system", "content": RESEARCHER_PROMPT.format(topic=topic)},
        {"role": "user", "content": f"Research this topic: {topic}"}
    ]

    # Use ga-express for faster research agents in production
    response = client.chat.completions.create(
        model="ga-express",
        messages=messages,
        tools=TOOLS
    )
    return response.choices[0].message.content

Pattern 2: Code Review Agent

An agent that reviews code, identifies bugs, and suggests fixes:

# build-ai-agents-deepseek-api/python/code_review_agent.py
CODE_REVIEW_PROMPT = """You are a senior code reviewer. Analyze the provided code for:
1. Security vulnerabilities
2. Performance issues
3. Best practice violations
4. Potential bugs

Provide specific line numbers and fix suggestions."""

def code_review_agent(code: str, language: str = "python") -> str:
    messages = [
        {"role": "system", "content": CODE_REVIEW_PROMPT},
        {"role": "user", "content": f"Analyze this {language} code:\n\n{code}"}
    ]

    # Use deepseek-reasoner for critical code reviews
    response = client.chat.completions.create(
        model="deepseek-reasoner",
        messages=messages,
        tools=TOOLS
    )
    return response.choices[0].message.content

Pattern 3: Customer Support Agent

An agent that handles support tickets by looking up order status, processing refunds, and generating responses:

# build-ai-agents-deepseek-api/python/support_agent.py
SUPPORT_PROMPT = """You are a customer support agent for an e-commerce platform.
You have tools to: look up orders, process refunds, and send emails.
Be polite, concise, and helpful. Only process refunds above $500 with manager approval."""

def support_agent(customer_message: str) -> str:
    messages = [
        {"role": "system", "content": SUPPORT_PROMPT},
        {"role": "user", "content": customer_message}
    ]

    # Use ga-standard for balanced support quality and cost
    response = client.chat.completions.create(
        model="ga-standard",
        messages=messages,
        tools=TOOLS,
        tool_choice="auto"
    )
    return response.choices[0].message.content

Current DeepSeek API Pricing

All pricing is per million tokens (input/output) through Global API:

| Model | advertiseUsdPerM Input | advertiseUsdPerM Output | |-------|------------------------|-------------------------| | deepseek-chat | $0.25 | $0.25 | | deepseek-reasoner | $2.50 | $2.50 | | deepseek-coder | $0.25 | $0.25 | | ga-economy | $0.125 | $0.125 | | ga-standard | $0.20 | $0.20 | | ga-express | $0.25 | $0.25 |

Prices sourced from Global API's current advertising rates. Backend billing may differ.

For the latest pricing and available models, visit Global API Pricing.


Getting Started with Global API

Building AI agents with DeepSeek is straightforward with the right infrastructure. Here's your checklist:

  1. Get an API key at global-apis.com — no credit card required to start
  2. Choose your model — deepseek-chat for cost-effective bulk tasks, deepseek-reasoner for complex reasoning
  3. Implement function calling — define tools, execute them, feed results back
  4. Add an agent loop — let the model decide when it's done
  5. Optimize with GA Fusion — use intelligent routing for production scale

Global API provides unified access to DeepSeek models (including V4 Flash, R1, and Coder), Qwen, Kimi, GLM, and 100+ other AI models through a single API endpoint. Sign up at https://global-apis.com and get started building your first AI agent today.


Conclusion

AI agents represent the next frontier of LLM-powered applications. With DeepSeek's function calling support, competitive pricing, and the option to use Global API's GA Fusion routing layer, you have everything you need to build sophisticated agents that can plan, reason, and take action in the real world.

Start small: build a single-step function caller first, then extend it into a full agent loop. The patterns in this guide transfer directly to production systems — from customer support bots to code review assistants to autonomous research agents.

Ready to build? Get your API key and try the code examples above today.

Related Articles

Related Articles

DeepSeek API Complete Beginner's Guide 2026: From Zero to Production →DeepSeek API Pricing Guide 2026: Complete Cost Breakdown & Savings Calculator →How to Migrate from OpenAI to DeepSeek in 10 Minutes (Complete Guide) →

Start Building with Global API

100 free credits on signup. 180+ AI models, one API key. PayPal accepted.

View Pricing →

© 2026 Global API. All rights reserved.