Analyze data với AI Analyze data with AI
Hướng dẫn chi tiết đồng bộ từ docs Cloudflare — mỗi section có backlink tới đúng vị trí trên trang gốc. Detailed guide synced from Cloudflare docs — each section links to the matching anchor on the official page.
← Danh mục ← CatalogGiải thích nhanh Quick context
Thuộc Developer Platform — thực hành triển khai code, API và dữ liệu trên edge/serverless. Tutorial «Analyze data với AI» giúp bạn làm quen luồng triển khai thật — phù hợp đọc trước khi mở tài liệu gốc tiếng Anh. Docs gốc chia khoảng 6 bước chính; bản tóm tắt dưới đây giúp bạn nắm khung trước khi làm theo từng lệnh.
Upload CSV files, generate analysis code with Claude, and return visualizations.
Lưu ý trước khi làm Notes before you start
- Đây là bản tóm tắt trên Orange Cloud Learning Hub — không thay thế tài liệu chính thức. This is a summary on Orange Cloud Learning Hub — it does not replace the official documentation.
- Luôn mở liên kết «Tài liệu gốc» bên dưới khi cần lệnh CLI, snippet code và ảnh minh họa đầy đủ. Open the Official docs link below for CLI commands, code snippets, and full screenshots.
- Docs Cloudflare cập nhật thường xuyên — đối chiếu ngày «Rà soát lần cuối» trên trang gốc khi triển khai production. Cloudflare docs change frequently — verify the Last reviewed date on the official page before production use.
Tài liệu gốc — rà soát lần cuối: 8 months ago Official docs — last reviewed: 8 months ago
Tổng quan Overview
Phần «Tổng quan» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "Overview" section below — open the official docs link for full screenshots and configuration tabs.
Build an AI-powered data analysis system that accepts CSV uploads, uses Claude to generate Python analysis code, executes it in sandboxes, and returns visualizations.
Time to complete: 25 minutes
Yêu cầu trước Prerequisites
Phần «Yêu cầu trước» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "Prerequisites" section below — open the official docs link for full screenshots and configuration tabs.
- Sign up for a Cloudflare account ↗.
- Install Node.js ↗.
Node.js version manager
Use a Node version manager like Volta ↗ or nvm ↗ to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.
You'll also need:
- An Anthropic API key ↗ for Claude
- Docker ↗ running locally
Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs)
1. Tạo your dự án 1. Create your project
Tạo new Sandbox SDK project:
Read the "1. Create your project" section below — open the official docs link for full screenshots and configuration tabs.
Create a new Sandbox SDK project:
npm yarn pnpm
npm create cloudflare@latest -- analyze-data --template=cloudflare/sandbox-sdk/examples/minimal yarn create cloudflare analyze-data --template=cloudflare/sandbox-sdk/examples/minimal pnpm create cloudflare@latest analyze-data --template=cloudflare/sandbox-sdk/examples/minimal Terminal window
cd analyze-data 2. Cài đặt dependencies 2. Install dependencies
Phần «Cài đặt dependencies» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "2. Install dependencies" section below — open the official docs link for full screenshots and configuration tabs.
npm yarn pnpm bun
npm i @anthropic-ai/sdk yarn add @anthropic-ai/sdk pnpm add @anthropic-ai/sdk bun add @anthropic-ai/sdk 3. Build analysis handler 3. Build the analysis handler
Phần «Build analysis handler» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "3. Build the analysis handler" section below — open the official docs link for full screenshots and configuration tabs.
Replace src/index.ts:
TypeScript
import { getSandbox, proxyToSandbox, type Sandbox } from "@cloudflare/sandbox";
import Anthropic from "@anthropic-ai/sdk";
export { Sandbox } from "@cloudflare/sandbox";
interface Env {
Sandbox: DurableObjectNamespace<Sandbox>;
ANTHROPIC_API_KEY: string;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const proxyResponse = await proxyToSandbox(request, env);
if (proxyResponse) return proxyResponse;
if (request.method !== "POST") {
return Response.json(
{ error: "POST CSV file and question" },
{ status: 405 },
);
}
try {
const formData = await request.formData();
const csvFile = formData.get("file") as File;
const question = formData.get("question") as string;
if (!csvFile || !question) {
return Response.json(
{ error: "Missing file or question" },
{ status: 400 },
);
}
// Upload CSV to sandbox
const sandbox = getSandbox(env.Sandbox, `analysis-${Date.now()}`);
const csvPath = "/workspace/data.csv";
await sandbox.writeFile(csvPath, await csvFile.text());
// Analyze CSV structure
const structure = await sandbox.exec(
`python3 -c "import pandas as pd; df = pd.read_csv('${csvPath}'); print(f'Rows: {len(df)}'); print(f'Columns: {list(df.columns)[:5]}')"`,
);
if (!structure.success) {
return Response.json(
{ error: "Failed to read CSV", details: structure.stderr },
{ status: 400 },
);
}
// Generate analysis code with Claude
const code = await generateAnalysisCode(
env.ANTHROPIC_API_KEY,
csvPath,
question,
structure.stdout,
);
// Write and execute the analysis code
await sandbox.writeFile("/workspace/analyze.py", code);
const result = await sandbox.exec("python /workspace/analyze.py");
if (!result.success) {
return Response.json(
{ error: "Analysis failed", details: result.stderr },
{ status: 500 },
);
}
async function streamToBase64(stream) {
const blob = await new Response(stream).blob();
const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer);
// Convert to base64
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
// Check for generated chart
let chart = null;
try {
const { content, mimeType } = await sandbox.readFile("/workspace/chart.png", {
encoding: "none"
});
chart = `data:${mimeType};base64,${await streamToBase64(content)}`;
} catch {
// No chart generated
}
await sandbox.destroy();
return Response.json({
success: true,
output: result.stdout,
chart,
code,
});
} catch (error: any) {
return Response.json({ error: error.message }, { status: 500 });
}
},
};
async function generateAnalysisCode(
apiKey: string,
csvPath: string,
question: string,
csvStructure: string,
): Promise<string> {
const anthropic = new Anthropic({ apiKey });
const response = await anthropic.messages.create({
model: "claude-sonnet-4-5",
max_tokens: 2048,
messages: [
{
role: "user",
content: `CSV at ${csvPath}:
${csvStructure}
Question: "${question}"
Generate Python code that:
- Reads CSV with pandas
- Answers the question
- Saves charts to /workspace/chart.png if helpful
- Prints findings to stdout
Use pandas, numpy, matplotlib.`,
},
],
tools: [
{
name: "generate_python_code",
description: "Generate Python code for data analysis",
input_schema: {
type 4. Thiết lập local environment variables 4. Set up local environment variables
Tạo .dev.vars file in your project root for local development:
Read the "4. Set up local environment variables" section below — open the official docs link for full screenshots and configuration tabs.
Create a .dev.vars file in your project root for local development:
Terminal window
echo "ANTHROPIC_API_KEY=your_api_key_here\nSANDBOX_TRANSPORT=rpc" > .dev.vars Replace yourapikey_here with your actual API key from the Anthropic Console ↗.
The SANDBOX_TRANSPORT is required to use the new file streaming APIs.
The .dev.vars file is automatically gitignored and only used during local development with npm run dev.
5. Kiểm thử cục bộ 5. Test locally
Phần «Kiểm thử cục bộ» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "5. Test locally" section below — open the official docs link for full screenshots and configuration tabs.
Download a sample CSV:
Terminal window
# Create a test CSV
echo "year,rating,title
2020,8.5,Movie A
2021,7.2,Movie B
2022,9.1,Movie C" > test.csv Start the dev server:
Terminal window
npm run dev Test with curl:
Terminal window
curl -X POST http://localhost:8787 \
-F "[email protected]" \
-F "question=What is the average rating by year?" Response:
{
"success": true,
"output": "Average ratings by year:\n2020: 8.5\n2021: 7.2\n2022: 9.1",
"chart": "data:image/png;base64,...",
"code": "import pandas as pd\nimport matplotlib.pyplot as plt\n..."
} 6. Deploy 6. Deploy
Phần «Deploy» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "6. Deploy" section below — open the official docs link for full screenshots and configuration tabs.
Deploy your Worker:
Terminal window
npx wrangler deploy Then set your Anthropic API key as a production secret:
Terminal window
npx wrangler secret put ANTHROPIC_API_KEY Paste your API key from the Anthropic Console ↗ when prompted.
Warning
Wait 2-3 minutes after first deployment for container provisioning.
What you built What you built
Phần «What you built» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "What you built" section below — open the official docs link for full screenshots and configuration tabs.
An AI data analysis system that:
- Uploads CSV files to sandboxes
- Uses Claude's tool calling to generate analysis code
- Executes Python with pandas and matplotlib
- Returns text output and visualizations
Bước tiếp theo Next steps
Phần «Bước tiếp theo» — đọc hướng dẫn bên dưới, dùng liên kết docs gốc để xem ảnh minh họa và tab cấu hình đầy đủ.
Read the "Next steps" section below — open the official docs link for full screenshots and configuration tabs.
- Code Interpreter API \- Use the built-in code interpreter
- File operations \- Advanced file handling
- Streaming output \- Real-time progress updates
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":{"@id":"/directory/","name":"Directory"}},{"@type":"ListItem","position":2,"item":{"@id":"/sandbox/","name":"Sandbox SDK"}},{"@type":"ListItem","position":3,"item":{"@id":"/sandbox/tutorials/","name":"Tutorials"}},{"@type":"ListItem","position":4,"item":{"@id":"/sandbox/tutorials/analyze-data-with-ai/","name":"Analyze data with AI"}}]} Liên kết liên quan (docs Cloudflare) Related links (Cloudflare docs)
Xem bản đầy đủ trên developers.cloudflare.com (ảnh, tab cấu hình). View the full guide on developers.cloudflare.com (images, config tabs).
Tài liệu gốc ↗ Official docs ↗