Tác nhân Deep Research của Gemini

Tác nhân Deep Research của Gemini tự động lập kế hoạch, thực hiện và tổng hợp các nhiệm vụ nghiên cứu nhiều bước. Được hỗ trợ bởi Gemini 3 Pro, tính năng này điều hướng các thông tin phức tạp bằng cách sử dụng tính năng tìm kiếm trên web và dữ liệu của riêng bạn để tạo ra các báo cáo chi tiết, có trích dẫn.

Các tác vụ nghiên cứu bao gồm tìm kiếm và đọc lặp đi lặp lại và có thể mất vài phút để hoàn thành. Bạn phải sử dụng background execution (thực thi trong nền) (đặt background=true) để chạy tác nhân một cách không đồng bộ và thăm dò kết quả. Hãy xem phần Xử lý các tác vụ chạy trong thời gian dài để biết thêm thông tin chi tiết.

Ví dụ sau đây cho thấy cách bắt đầu một tác vụ nghiên cứu ở chế độ nền và thăm dò kết quả.

Python

import time
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    input="Research the history of Google TPUs.",
    agent='deep-research-pro-preview-12-2025',
    background=True
)

print(f"Research started: {interaction.id}")

while True:
    interaction = client.interactions.get(interaction.id)
    if interaction.status == "completed":
        print(interaction.outputs[-1].text)
        break
    elif interaction.status == "failed":
        print(f"Research failed: {interaction.error}")
        break
    time.sleep(10)

JavaScript

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    input: 'Research the history of Google TPUs.',
    agent: 'deep-research-pro-preview-12-2025',
    background: true
});

console.log(`Research started: ${interaction.id}`);

while (true) {
    const result = await client.interactions.get(interaction.id);
    if (result.status === 'completed') {
        console.log(result.outputs[result.outputs.length - 1].text);
        break;
    } else if (result.status === 'failed') {
        console.log(`Research failed: ${result.error}`);
        break;
    }
    await new Promise(resolve => setTimeout(resolve, 10000));
}

REST

# 1. Start the research task
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Research the history of Google TPUs.",
    "agent": "deep-research-pro-preview-12-2025",
    "background": true
}'

# 2. Poll for results (Replace INTERACTION_ID)
# curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID" \
# -H "x-goog-api-key: $GEMINI_API_KEY"

Nghiên cứu bằng dữ liệu của riêng bạn

Deep Research có quyền truy cập vào nhiều công cụ. Theo mặc định, tác nhân có quyền truy cập vào thông tin trên Internet công cộng bằng cách sử dụng công cụ google_searchurl_context. Theo mặc định, bạn không cần chỉ định các công cụ này. Tuy nhiên, nếu muốn cấp cho tác nhân quyền truy cập vào dữ liệu của riêng bạn bằng cách sử dụng công cụ Tìm kiếm tệp, bạn sẽ cần thêm công cụ đó như trong ví dụ sau.

Python

import time
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    input="Compare our 2025 fiscal year report against current public web news.",
    agent="deep-research-pro-preview-12-2025",
    background=True,
    tools=[
        {
            "type": "file_search",
            "file_search_store_names": ['fileSearchStores/my-store-name']
        }
    ]
)

JavaScript

const interaction = await client.interactions.create({
    input: 'Compare our 2025 fiscal year report against current public web news.',
    agent: 'deep-research-pro-preview-12-2025',
    background: true,
    tools: [
        { type: 'file_search', file_search_store_names: ['fileSearchStores/my-store-name'] },
    ]
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Compare our 2025 fiscal year report against current public web news.",
    "agent": "deep-research-pro-preview-12-2025",
    "background": true,
    "tools": [
        {"type": "file_search", "file_search_store_names": ["fileSearchStores/my-store-name"]},
    ]
}'

Khả năng điều hướng và định dạng

Bạn có thể điều hướng đầu ra của tác nhân bằng cách cung cấp hướng dẫn định dạng cụ thể trong câu lệnh. Nhờ đó, bạn có thể sắp xếp báo cáo thành các phần và phần phụ cụ thể, thêm bảng dữ liệu hoặc điều chỉnh giọng điệu cho nhiều đối tượng (ví dụ: "technical" (kỹ thuật), "executive" (điều hành), "casual" (bình thường).

Xác định rõ định dạng đầu ra mong muốn trong văn bản đầu vào.

Python

prompt = """
Research the competitive landscape of EV batteries.

Format the output as a technical report with the following structure:
1. Executive Summary
2. Key Players (Must include a data table comparing capacity and chemistry)
3. Supply Chain Risks
"""

interaction = client.interactions.create(
    input=prompt,
    agent="deep-research-pro-preview-12-2025",
    background=True
)

JavaScript

const prompt = `
Research the competitive landscape of EV batteries.

Format the output as a technical report with the following structure:
1. Executive Summary
2. Key Players (Must include a data table comparing capacity and chemistry)
3. Supply Chain Risks
`;

const interaction = await client.interactions.create({
    input: prompt,
    agent: 'deep-research-pro-preview-12-2025',
    background: true,
});

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Research the competitive landscape of EV batteries.\n\nFormat the output as a technical report with the following structure: \n1. Executive Summary\n2. Key Players (Must include a data table comparing capacity and chemistry)\n3. Supply Chain Risks",
    "agent": "deep-research-pro-preview-12-2025",
    "background": true
}'

Xử lý các tác vụ chạy trong thời gian dài

Deep Research là một quy trình nhiều bước bao gồm lập kế hoạch, tìm kiếm, đọc và viết. Chu kỳ này thường vượt quá giới hạn thời gian chờ tiêu chuẩn của các lệnh gọi API đồng bộ.

Nhân viên hỗ trợ bắt buộc phải sử dụng background=True. API này sẽ trả về ngay một đối tượng Interaction một phần. Bạn có thể dùng thuộc tính id để truy xuất một lượt tương tác cho hoạt động bỏ phiếu. Trạng thái tương tác sẽ chuyển từ in_progress sang completed hoặc failed.

Phát trực tiếp

Tính năng Deep Research hỗ trợ truyền trực tuyến để nhận thông tin cập nhật theo thời gian thực về tiến trình nghiên cứu. Bạn phải đặt stream=Truebackground=True.

Ví dụ sau đây cho biết cách bắt đầu một tác vụ nghiên cứu và xử lý luồng dữ liệu. Điều quan trọng là ví dụ này minh hoạ cách theo dõi interaction_id từ sự kiện interaction.start. Bạn sẽ cần mã nhận dạng này để tiếp tục phát trực tiếp nếu mạng bị gián đoạn. Mã này cũng giới thiệu một biến event_id cho phép bạn tiếp tục từ điểm cụ thể mà bạn đã ngắt kết nối.

Python

stream = client.interactions.create(
    input="Research the history of Google TPUs.",
    agent="deep-research-pro-preview-12-2025",
    background=True,
    stream=True,
    agent_config={
        "type": "deep-research",
        "thinking_summaries": "auto"
    }
)

interaction_id = None
last_event_id = None

for chunk in stream:
    if chunk.event_type == "interaction.start":
        interaction_id = chunk.interaction.id
        print(f"Interaction started: {interaction_id}")

    if chunk.event_id:
        last_event_id = chunk.event_id

    if chunk.event_type == "content.delta":
        if chunk.delta.type == "text":
            print(chunk.delta.text, end="", flush=True)
        elif chunk.delta.type == "thought_summary":
            print(f"Thought: {chunk.delta.content.text}", flush=True)

    elif chunk.event_type == "interaction.complete":
        print("\nResearch Complete")

JavaScript

const stream = await client.interactions.create({
    input: 'Research the history of Google TPUs.',
    agent: 'deep-research-pro-preview-12-2025',
    background: true,
    stream: true,
    agent_config: {
        type: 'deep-research',
        thinking_summaries: 'auto'
    }
});

let interactionId;
let lastEventId;

for await (const chunk of stream) {
    // 1. Capture Interaction ID
    if (chunk.event_type === 'interaction.start') {
        interactionId = chunk.interaction.id;
        console.log(`Interaction started: ${interactionId}`);
    }

    // 2. Track IDs for potential reconnection
    if (chunk.event_id) lastEventId = chunk.event_id;

    // 3. Handle Content
    if (chunk.event_type === 'content.delta') {
        if (chunk.delta.type === 'text') {
            process.stdout.write(chunk.delta.text);
        } else if (chunk.delta.type === 'thought_summary') {
            console.log(`Thought: ${chunk.delta.content.text}`);
        }
    } else if (chunk.event_type === 'interaction.complete') {
        console.log('\nResearch Complete');
    }
}

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Research the history of Google TPUs.",
    "agent": "deep-research-pro-preview-12-2025",
    "background": true,
    "stream": true,
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto"
    }
}'
# Note: Look for the 'interaction.start' event to get the interaction ID.

Đang kết nối lại với luồng phát

Tình trạng gián đoạn mạng có thể xảy ra trong các tác vụ nghiên cứu kéo dài. Để xử lý lỗi này một cách thoả đáng, ứng dụng của bạn phải bắt lỗi kết nối và tiếp tục truyền phát bằng client.interactions.get().

Bạn phải cung cấp 2 giá trị để tiếp tục:

  1. Mã nhận dạng lượt tương tác: Thu được từ sự kiện interaction.start trong luồng ban đầu.
  2. Mã sự kiện gần đây nhất: Mã của sự kiện được xử lý thành công gần đây nhất. Thao tác này yêu cầu máy chủ tiếp tục gửi các sự kiện sau thời điểm cụ thể đó. Nếu không cung cấp, bạn sẽ nhận được phần đầu của luồng.

Các ví dụ sau đây minh hoạ một mẫu có khả năng phục hồi: cố gắng truyền trực tuyến yêu cầu create ban đầu và quay lại vòng lặp get nếu kết nối bị gián đoạn.

Python

import time
from google import genai

client = genai.Client()

# Configuration
agent_name = 'deep-research-pro-preview-12-2025'
prompt = 'Compare golang SDK test frameworks'

# State tracking
last_event_id = None
interaction_id = None
is_complete = False

def process_stream(event_stream):
    """Helper to process events from any stream source."""
    global last_event_id, interaction_id, is_complete
    for event in event_stream:
        # Capture Interaction ID
        if event.event_type == "interaction.start":
            interaction_id = event.interaction.id
            print(f"Interaction started: {interaction_id}")

        # Capture Event ID
        if event.event_id:
            last_event_id = event.event_id

        # Print content
        if event.event_type == "content.delta":
            if event.delta.type == "text":
                print(event.delta.text, end="", flush=True)
            elif event.delta.type == "thought_summary":
                print(f"Thought: {event.delta.content.text}", flush=True)

        # Check completion
        if event.event_type in ['interaction.complete', 'error']:
            is_complete = True

# 1. Attempt initial streaming request
try:
    print("Starting Research...")
    initial_stream = client.interactions.create(
        input=prompt,
        agent=agent_name,
        background=True,
        stream=True,
        agent_config={
            "type": "deep-research",
            "thinking_summaries": "auto"
        }
    )
    process_stream(initial_stream)
except Exception as e:
    print(f"\nInitial connection dropped: {e}")

# 2. Reconnection Loop
# If the code reaches here and is_complete is False, we resume using .get()
while not is_complete and interaction_id:
    print(f"\nConnection lost. Resuming from event {last_event_id}...")
    time.sleep(2) 

    try:
        resume_stream = client.interactions.get(
            id=interaction_id,
            stream=True,
            last_event_id=last_event_id
        )
        process_stream(resume_stream)
    except Exception as e:
        print(f"Reconnection failed, retrying... ({e})")

JavaScript

let lastEventId;
let interactionId;
let isComplete = false;

// Helper to handle the event logic
const handleStream = async (stream) => {
    for await (const chunk of stream) {
        if (chunk.event_type === 'interaction.start') {
            interactionId = chunk.interaction.id;
        }
        if (chunk.event_id) lastEventId = chunk.event_id;

        if (chunk.event_type === 'content.delta') {
            if (chunk.delta.type === 'text') {
                process.stdout.write(chunk.delta.text);
            } else if (chunk.delta.type === 'thought_summary') {
                console.log(`Thought: ${chunk.delta.content.text}`);
            }
        } else if (chunk.event_type === 'interaction.complete') {
            isComplete = true;
        }
    }
};

// 1. Start the task with streaming
try {
    const stream = await client.interactions.create({
        input: 'Compare golang SDK test frameworks',
        agent: 'deep-research-pro-preview-12-2025',
        background: true,
        stream: true,
        agent_config: {
            type: 'deep-research',
            thinking_summaries: 'auto'
        }
    });
    await handleStream(stream);
} catch (e) {
    console.log('\nInitial stream interrupted.');
}

// 2. Reconnect Loop
while (!isComplete && interactionId) {
    console.log(`\nReconnecting to interaction ${interactionId} from event ${lastEventId}...`);
    try {
        const stream = await client.interactions.get(interactionId, {
            stream: true,
            last_event_id: lastEventId
        });
        await handleStream(stream);
    } catch (e) {
        console.log('Reconnection failed, retrying in 2s...');
        await new Promise(resolve => setTimeout(resolve, 2000));
    }
}

REST

# 1. Start the research task (Initial Stream)
# Watch for event: interaction.start to get the INTERACTION_ID
# Watch for "event_id" fields to get the LAST_EVENT_ID
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions?alt=sse" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Compare golang SDK test frameworks",
    "agent": "deep-research-pro-preview-12-2025",
    "background": true,
    "stream": true,
    "agent_config": {
        "type": "deep-research",
        "thinking_summaries": "auto"
    }
}'

# ... Connection interrupted ...

# 2. Reconnect (Resume Stream)
# Pass the INTERACTION_ID and the LAST_EVENT_ID you saved.
curl -X GET "https://generativelanguage.googleapis.com/v1beta/interactions/INTERACTION_ID?stream=true&last_event_id=LAST_EVENT_ID&alt=sse" \
-H "x-goog-api-key: $GEMINI_API_KEY"

Câu hỏi nối tiếp và lượt tương tác

Bạn có thể tiếp tục cuộc trò chuyện sau khi nhân viên hỗ trợ gửi báo cáo cuối cùng bằng cách sử dụng previous_interaction_id. Nhờ đó, bạn có thể yêu cầu làm rõ, tóm tắt hoặc giải thích chi tiết về các phần cụ thể của nghiên cứu mà không cần bắt đầu lại toàn bộ nhiệm vụ.

Python

import time
from google import genai

client = genai.Client()

interaction = client.interactions.create(
    input="Can you elaborate on the second point in the report?",
    model="gemini-3-pro-preview",
    previous_interaction_id="COMPLETED_INTERACTION_ID"
)

print(interaction.outputs[-1].text)

JavaScript

const interaction = await client.interactions.create({
    input: 'Can you elaborate on the second point in the report?',
    agent: 'deep-research-pro-preview-12-2025',
    previous_interaction_id: 'COMPLETED_INTERACTION_ID'
});
console.log(interaction.outputs[-1].text);

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
    "input": "Can you elaborate on the second point in the report?",
    "agent": "deep-research-pro-preview-12-2025",
    "previous_interaction_id": "COMPLETED_INTERACTION_ID"
}'

Trường hợp nên dùng Tác nhân Deep Research của Gemini

Deep Research là một tác nhân, chứ không chỉ là một mô hình. Công cụ này phù hợp nhất với những khối lượng công việc yêu cầu phương pháp "nhà phân tích trong hộp" thay vì trò chuyện có độ trễ thấp.

Tính năng Các mô hình Gemini tiêu chuẩn Tác nhân Deep Research của Gemini
Độ trễ Giây Phút (Không đồng bộ/Nền)
Quy trình Tạo -> Đầu ra Lập kế hoạch -> Tìm kiếm -> Đọc -> Lặp lại -> Đầu ra
Đầu ra Văn bản trò chuyện, mã, bản tóm tắt ngắn Báo cáo chi tiết, phân tích dài, bảng so sánh
Phù hợp nhất cho Chatbot, trích xuất, viết sáng tạo Phân tích thị trường, thẩm định, đánh giá tài liệu, bối cảnh cạnh tranh

Tình trạng còn hàng và giá

  • Phạm vi cung cấp: Có thể truy cập bằng Interactions API trong Google AI Studio và Gemini API.
  • Giá: Xem trang Định giá để biết mức giá và thông tin chi tiết cụ thể.

Lưu ý về an toàn

Việc cấp cho một đặc vụ quyền truy cập vào web và các tệp riêng tư của bạn đòi hỏi bạn phải cân nhắc kỹ lưỡng các rủi ro về an toàn.

  • Tấn công bằng cách chèn câu lệnh sử dụng tệp: Trợ lý sẽ đọc nội dung của các tệp mà bạn cung cấp. Đảm bảo rằng các tài liệu được tải lên (tệp PDF, tệp văn bản) đến từ các nguồn đáng tin cậy. Một tệp độc hại có thể chứa văn bản ẩn được thiết kế để thao túng đầu ra của tác nhân.
  • Rủi ro về nội dung trên web: Đặc vụ tìm kiếm trên web công khai. Mặc dù chúng tôi triển khai các bộ lọc an toàn mạnh mẽ, nhưng vẫn có nguy cơ là tác nhân có thể gặp phải và xử lý các trang web độc hại. Bạn nên xem xét citations được cung cấp trong câu trả lời để xác minh các nguồn.
  • Trích xuất: Hãy thận trọng khi yêu cầu tác nhân tóm tắt dữ liệu nội bộ nhạy cảm nếu bạn cũng cho phép tác nhân duyệt web.

Các phương pháp hay nhất

  • Nhắc về những thông tin chưa biết: Hướng dẫn nhân viên cách xử lý dữ liệu bị thiếu. Ví dụ: hãy thêm "Nếu không có số liệu cụ thể cho năm 2025, hãy nêu rõ rằng đó là số liệu dự đoán hoặc không có sẵn thay vì ước tính" vào câu lệnh của bạn.
  • Cung cấp bối cảnh: Hỗ trợ nghiên cứu của tác nhân bằng cách cung cấp thông tin cơ bản hoặc các ràng buộc ngay trong câu lệnh đầu vào.
  • Thông tin đầu vào đa phương thức Deep Research Agent hỗ trợ thông tin đầu vào đa phương thức. Hãy sử dụng một cách thận trọng vì điều này làm tăng chi phí và nguy cơ tràn cửa sổ ngữ cảnh.

Các điểm hạn chế

  • Trạng thái thử nghiệm: Interactions API đang ở giai đoạn thử nghiệm công khai. Các tính năng và lược đồ có thể thay đổi.
  • Công cụ tuỳ chỉnh: Hiện tại, bạn không thể cung cấp các công cụ gọi hàm tuỳ chỉnh hoặc máy chủ MCP (Giao thức ngữ cảnh mô hình) từ xa cho tác nhân Nghiên cứu chuyên sâu.
  • Đầu ra có cấu trúc và phê duyệt kế hoạch: Hiện tại, Deep Research Agent không hỗ trợ lập kế hoạch hoặc đầu ra có cấu trúc được con người phê duyệt.
  • Thời gian nghiên cứu tối đa: Deep Research có thời gian nghiên cứu tối đa là 60 phút. Hầu hết các tác vụ sẽ hoàn tất trong vòng 20 phút.
  • Yêu cầu về cửa hàng: Việc thực thi tác nhân bằng background=True yêu cầu store=True.
  • Google Tìm kiếm: Google Tìm kiếm được bật theo mặc định và các hạn chế cụ thể áp dụng cho kết quả có căn cứ.
  • Đầu vào âm thanh: Không hỗ trợ đầu vào âm thanh.

Bước tiếp theo