Tutorial12 min readDecember 15, 2024

Complete Guide to Integrating Deep Research into AI Agents

Step-by-step tutorial on building AI agents that use Deep Research API for real-time information retrieval.

UnforgeAPI Team

Share:

Introduction

Building AI agents that can access real-time information is a game-changer. This guide shows you how to integrate Deep Research API into your agent architecture.

Prerequisites

Before starting, you'll need:

  • Deep Research API key (Get one here)
  • Node.js 18+ or Python 3.8+
  • Basic understanding of REST APIs
  • An agent framework (LangChain, AutoGPT, or custom)

Architecture Overview

┌─────────────┐
│   Agent     │
│  Framework   │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│  Deep       │
│  Research   │
│    API      │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│   Web &     │
│  LLM APIs   │
└─────────────┘

Step 1: Setup

Install Dependencies

npm install @unforgeapi/deep-research
# or
yarn add @unforgeapi/deep-research

Configure Environment

# .env file
DEEP_RESEARCH_API_KEY=your_api_key_here

Step 2: Basic Integration

Initialize Client

import { DeepResearchClient } from '@unforgeapi/deep-research'

const client = new DeepResearchClient({
  apiKey: process.env.DEEP_RESEARCH_API_KEY
})

Simple Query

const response = await client.research({
  query: "What's the current price of Bitcoin?"
})

console.log(response.answer)
// "Bitcoin is currently trading at $95,000..."

Step 3: Agent Integration

Define Agent Tools

import { Tool } from '@langchain/core'

const researchTool: Tool = {
  name: "deep_research",
  description: "Search the web and get structured research data",
  func: async (input: string) => {
    const response = await client.research({
      query: input,
      schema: {
        answer: "string",
        sources: "string[]",
        confidence: "number"
      }
    })
    return JSON.stringify(response)
  }
}

Create Agent

import { Agent } from '@langchain/core'

const agent = new Agent({
  name: "Research Agent",
  tools: [researchTool],
  llm: yourLLM,
  systemPrompt: `You are a research assistant. Use the deep_research tool to find current information.`
})

Step 4: Advanced Features

Custom Schemas

const financialData = await client.research({
  query: "Tesla stock analysis",
  mode: "schema",
  schema: {
    current_price: "number",
    daily_change: "string",
    volume: "number",
    market_cap: "number",
    pe_ratio: "number"
  }
})

// Returns structured financial data
// No parsing needed

Extraction Mode

const productFeatures = await client.research({
  query: "iPhone 16 features",
  mode: "extract",
  extract: ["display", "camera", "battery", "processor", "storage"]
})

// Returns clean array of features
// ["6.7-inch OLED", "48MP camera", ...]

Webhook Delivery

const response = await client.research({
  query: "Your query",
  webhook: "https://your-agent.com/callback"
})

// Result POSTed to your webhook when ready
// Agent continues without waiting

Step 5: Error Handling

try {
  const response = await client.research({ query: "..." })
  
  // Validate response
  if (!response.answer) {
    throw new Error("No answer in response")
  }
  
  // Use data
  console.log(response.answer)
  
} catch (error) {
  if (error.status === 429) {
    // Rate limited - implement backoff
    await sleep(5000)
    return retry()
  }
  
  console.error("Research failed:", error)
}

Step 6: Production Tips

Caching

const cache = new Map()

async function getCachedResearch(query: string) {
  if (cache.has(query)) {
    return cache.get(query)
  }
  
  const result = await client.research({ query })
  cache.set(query, result)
  return result
}

Monitoring

import { monitor } from '@unforgeapi/deep-research'

monitor({
  apiKey: process.env.DEEP_RESEARCH_API_KEY,
  onUsage: (stats) => {
    console.log("Usage:", stats)
  },
  onError: (error) => {
    console.error("Error:", error)
  }
})

Rate Limiting

import pLimit from 'p-limit'

const limit = pLimit(5) // 5 concurrent requests

const results = await Promise.all([
  limit(() => client.research({ query: "Q1" })),
  limit(() => client.research({ query: "Q2" })),
  limit(() => client.research({ query: "Q3" })),
  limit(() => client.research({ query: "Q4" }))
])

Step 7: Testing

Unit Tests

import { describe, it, expect } from 'vitest'

describe('DeepResearchClient', () => {
  it('should return structured data', async () => {
    const response = await client.research({
      query: "Test query",
      schema: { answer: "string" }
    })
    
    expect(response).toHaveProperty('answer')
    expect(typeof response.answer).toBe('string')
  })
  
  it('should handle errors', async () => {
    await expect(async () => {
      await client.research({ query: "" })
    }).rejects.toThrow()
  })
})

Integration Tests

import { test } from '@playwright/test'

test('agent workflow', async ({ page }) => {
  await page.goto('/agent')
  
  // Trigger research
  await page.fill('input[name="query"]', 'Bitcoin price')
  await page.click('button[type="submit"]')
  
  // Wait for result
  await page.waitForSelector('[data-testid="research-result"]')
  
  // Verify result
  const result = await page.textContent('[data-testid="research-result"]')
  expect(result).toContain('$')
})

Next Steps

  1. Deploy: Deploy your agent to production
  2. Monitor: Track usage and errors
  3. Optimize: Cache results, handle rate limits
  4. Scale: Add more agents or features

Get Started

Ready to build your first AI agent with Deep Research?

Get Your API Key

Read Full Documentation

Tags:TutorialAI AgentsDeep Research

Ready to Build with AI?

Join developers using UnforgeAPI to ship intelligent applications faster with our Hybrid RAG engine.