# Kiểm tra tài khoản và kết quả đã lưu bằng SDK

Kiểm tra chi phí, ghi lại từng nỗ lực và đọc kết quả đã lưu mà không có một kết quả khác API Gọi đi.

Tài liệu tham khảo chính điển: https://flashdata.dev/vi/docs/guides/sdk-operations
Xem lại: 2026-11-04 by FlashData

<a id="prepare"></a>

## Trước khi bắt đầu

Dùng dự án đã cài đặt SDK và FLASHDATA_API_KEY của bạn SDK Khởi động nhanh. Chọn một ngôn ngữ bên dưới. Mỗi thư mục chạy mới tượng trưng cho một việc tìm kiếm đã định; sử dụng lại một thư mục đã có trước khi yêu cầu.

- [Go SDK thiết lập](https://flashdata.dev/vi/docs/guides/flashdata-go/reference.md)
- [Python SDK thiết lập](https://flashdata.dev/vi/docs/guides/flashdata-python/reference.md)
- [TypeScript SDK thiết lập](https://flashdata.dev/vi/docs/guides/flashdata-typescript/reference.md)

<a id="check"></a>

## 1. Kiểm tra quyền truy cập và chi phí hiện tại

Lưu và chạy kiểm tra cho của bạn SDK. Nó đọc quyền hạn, sự số dư và giá của một Google Search. Tiếp tục chỉ sau khi kiểm tra truy cập được qua; những kiểm tra này không gửi một truy vấn hoặc tín dụng dự trữ được trả tiền.

### Python

#### check_access.py

```python
import os
import sys
from flashdata import FlashData, APIError

def main():
    key = os.environ.get("FLASHDATA_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set FLASHDATA_API_KEY in this terminal.")
    with FlashData(api_key=key) as client:
        access = client.account.access()
        if "google_search" not in access["sources"]:
            raise RuntimeError("This key needs google_search permission.")
        balance = client.account.balance()
        pricing = client.account.pricing(source="google_search", request_count=1)
    price = next((p for p in pricing["prices"]
                  if p["source"] == "google_search" and p["available"]), None)
    cost = price.get("estimatedCredits") if price else None
    if cost is None:
        raise RuntimeError("No current price is available; stop here.")
    available = balance["availableCredits"]
    print(f"Available credits: {available}")
    print(f"One search: {cost} credits")
    if available < cost:
        raise RuntimeError("Insufficient credits. Review Billing.")
    print("Access check passed. No paid query submitted.")

if __name__ == "__main__":
    try:
        main()
    except APIError as error:
        print(f"HTTP {error.status_code}; code={error.code}; "
              f"request_id={error.request_id}; Retry-After={error.retry_after}",
              file=sys.stderr)
        sys.exit(1)
    except Exception as error:
        print(f"{type(error).__name__}: {error}", file=sys.stderr)
        sys.exit(1)
```

#### Linux / macOS

```bash
.venv/bin/python check_access.py
```

#### Windows PowerShell

```powershell
.\.venv\Scripts\python.exe check_access.py
```


### TypeScript / JavaScript

#### check-access.mjs

```javascript
import { FlashData, APIError } from '@flashdata-dev/sdk';

try {
  const apiKey = process.env.FLASHDATA_API_KEY?.trim();
  if (!apiKey) throw new Error('Set FLASHDATA_API_KEY in this terminal.');
  const client = new FlashData({ apiKey });
  const access = await client.account.access();
  if (!access.sources.includes('google_search')) {
    throw new Error('This key needs google_search permission.');
  }
  const balance = await client.account.balance();
  const pricing = await client.account.pricing({ source: 'google_search', request_count: 1 });
  const price = pricing.prices.find(p => p.source === 'google_search' && p.available);
  const cost = price?.estimatedCredits;
  if (cost == null) throw new Error('No current price is available; stop here.');
  console.log('Available credits:', balance.availableCredits);
  console.log('One search:', cost, 'credits');
  if (balance.availableCredits < cost) throw new Error('Insufficient credits. Review Billing.');
  console.log('Access check passed. No paid query submitted.');
} catch (error) {
  if (error instanceof APIError) {
    console.error('HTTP', error.statusCode, 'code:', error.code,
      'request_id:', error.requestId, 'Retry-After:', error.retryAfter);
  } else {
    console.error(error instanceof Error ? error.message : String(error));
  }
  process.exitCode = 1;
}
```

#### Chạy

```bash
node check-access.mjs
```


### Go

Tạo cmd/check và lưu tập tin này vào đó.

#### cmd/check/main.go

```go
package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "slices"
    "time"

    flashdata "github.com/flashdatadev/flashdata-go"
)

func main() {
    key := os.Getenv("FLASHDATA_API_KEY")
    if key == "" {
        log.Fatal("Set FLASHDATA_API_KEY in this terminal.")
    }
    client, err := flashdata.New(flashdata.Options{APIKey: key})
    if err != nil {
        log.Fatal(err)
    }
    ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
    defer cancel()

    identity, err := client.Account.Identity(ctx)
    if err != nil {
        log.Fatal(err)
    }
    if identity.Access != "ready" || !slices.Contains(identity.Scopes, flashdata.SourceGoogleSearch) {
        log.Fatal("This key is not ready for google_search. Check its status and permissions.")
    }
    balance, err := client.Account.Balance(ctx)
    if err != nil {
        log.Fatal(err)
    }
    pricing, err := client.Account.Pricing(ctx, flashdata.PricingParams{
        Source: flashdata.SourceGoogleSearch, RequestCount: 1,
    })
    if err != nil {
        log.Fatal(err)
    }
    if len(pricing.Prices) != 1 || pricing.Prices[0].Source != "google_search" ||
        !pricing.Prices[0].Available || pricing.Prices[0].EstimatedCredits == nil {
        log.Fatal("A current Google Search price is unavailable. Do not submit yet.")
    }
    cost := *pricing.Prices[0].EstimatedCredits
    fmt.Printf("Account: %s (%s)\n", identity.AccountID, identity.AccountType)
    fmt.Printf("Available credits: %g\nOne search: %g credits\n", balance.AvailableCredits, cost)
    if balance.AvailableCredits < cost {
        log.Fatal("Insufficient credits. Check Billing or claim existing trial access.")
    }
    fmt.Println("Access check passed. No paid query submitted.")
}
```

#### Chạy

```bash
go run ./cmd/check
```



<a id="save"></a>

## 2. Chạy với thư mục xuất mới

Chạy một trong những chương trình này sau khi kiểm tra xong. Nó tạo thư mục trước khi gửi, ghi lại yêu cầu, rồi lưu lại câu trả lời. Giữ thư mục vào thất bại: xoá nó hoặc chọn một điều mới cho phép một yêu cầu có thể tính toán khác.

### Python

#### archive_search.py

```python
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from flashdata import FlashData, APIError, SubmissionUnknownError

def main():
    key = os.environ.get("FLASHDATA_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set FLASHDATA_API_KEY before running.")
    directory = Path(sys.argv[1] if len(sys.argv) > 1 else "runs/research-001")
    directory.mkdir(mode=0o700, parents=True, exist_ok=False)

    def save(name, value):
        with (directory / name).open("x", encoding="utf-8") as output:
            json.dump(value, output, ensure_ascii=False, indent=2)

    request = {"source": "google_search", "query": "battery recycling research",
               "params": {"num": 5}}
    save("request.json", request)
    save("intent.json", {"state": "dispatching",
                         "startedAt": datetime.now(timezone.utc).isoformat()})
    try:
        with FlashData(api_key=key) as client:
            response = client.google.search(request["query"], **request["params"])
    except (APIError, SubmissionUnknownError) as error:
        detail = {"kind": type(error).__name__}
        if isinstance(error, APIError):
            detail.update(code=error.code, httpStatus=error.status_code,
                          requestId=error.request_id, retryAfter=error.retry_after)
        save("error.json", detail)
        raise RuntimeError("Inspect the saved attempt and History before retrying.") from None
    save("result.json", response)
    if response.get("status") != "done":
        raise RuntimeError("Response saved; inspect its status before proceeding.")
    print("Saved:", directory / "result.json")
    print("Usage:", response.get("usage"))

if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print(f"{type(error).__name__}: {error}", file=sys.stderr)
        sys.exit(1)
```

#### Linux / macOS

```bash
.venv/bin/python archive_search.py runs/research-001
```

#### Windows PowerShell

```powershell
.\.venv\Scripts\python.exe archive_search.py runs/research-001
```


### TypeScript / JavaScript

Lưu chương trình hệ điều hành âm thanh này vào một trong hai JavaScript hay TypeScript dự án. Nó sử dụng cùng một gói @flashdata-dev/sdk.

#### archive-search.mjs

```javascript
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { FlashData, APIError, SubmissionUnknownError } from '@flashdata-dev/sdk';

try {
  const apiKey = process.env.FLASHDATA_API_KEY?.trim();
  if (!apiKey) throw new Error('Set FLASHDATA_API_KEY before running.');
  const directory = process.argv[2] || 'runs/research-001';
  await mkdir(dirname(directory), { recursive: true });
  await mkdir(directory, { mode: 0o700 }); // Existing attempt: stop before any API call.
  const save = (name, value) => writeFile(join(directory, name),
    JSON.stringify(value, null, 2), { flag: 'wx', mode: 0o600 });
  const request = { source: 'google_search', query: 'battery recycling research',
    params: { num: 5 } };
  await save('request.json', request);
  await save('intent.json', { state: 'dispatching', startedAt: new Date().toISOString() });
  const client = new FlashData({ apiKey });
  let response;
  try {
    response = await client.google.search({ query: request.query, ...request.params });
  } catch (error) {
    const detail = { kind: error instanceof SubmissionUnknownError
      ? 'SubmissionUnknownError' : error instanceof APIError ? 'APIError' : 'ClientError' };
    if (error instanceof APIError) Object.assign(detail, {
      code: error.code, httpStatus: error.statusCode,
      requestId: error.requestId, retryAfter: error.retryAfter,
    });
    await save('error.json', detail);
    throw new Error('Inspect the saved attempt and History before retrying.');
  }
  await save('result.json', response);
  if (response.status !== 'done') throw new Error('Response saved; inspect its status.');
  console.log('Saved:', join(directory, 'result.json'));
  console.log('Usage:', response.usage);
} catch (error) {
  console.error(error instanceof Error ? error.message : 'Inspect this attempt.');
  process.exitCode = 1;
}
```

#### Chạy

```bash
node archive-search.mjs runs/research-001
```


### Go

Tạo cmd/archive Vì vậy điểm nhập này phải tách biệt với chương trình "Sự khởi đầu nhanh chóng" của bạn.

#### cmd/archive/main.go

```go
package main

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "os"
    "path/filepath"
    "time"
    flashdata "github.com/flashdatadev/flashdata-go"
)

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func run() error {
    key := os.Getenv("FLASHDATA_API_KEY")
    if key == "" { return errors.New("set FLASHDATA_API_KEY before running") }
    directory := "runs/research-001"
    if len(os.Args) > 1 { directory = os.Args[1] }
    if err := os.MkdirAll(filepath.Dir(directory), 0700); err != nil { return err }
    if err := os.Mkdir(directory, 0700); err != nil { return err }
    save := func(name string, value any) error {
        file, err := os.OpenFile(filepath.Join(directory, name), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
        if err != nil { return err }
        err = json.NewEncoder(file).Encode(value)
        closeErr := file.Close()
        if err != nil { return err }
        return closeErr
    }
    query := flashdata.GoogleSearchInput{Query: "battery recycling research",
        Params: &flashdata.GoogleSearchParams{Num: flashdata.Ptr(int64(5))}}
    if err := save("request.json", map[string]any{"source": "google_search",
        "query": query.Query, "params": query.Params}); err != nil { return err }
    if err := save("intent.json", map[string]string{"state": "dispatching",
        "startedAt": time.Now().UTC().Format(time.RFC3339)}); err != nil { return err }
    client, err := flashdata.New(flashdata.Options{APIKey: key})
    if err != nil { return err }
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    defer cancel()
    result, err := client.Google.Search(ctx, query)
    if err != nil {
        detail := map[string]any{"kind": "ClientError"}
        var api *flashdata.APIError
        var unknown *flashdata.SubmissionUnknownError
        if errors.As(err, &api) {
            detail = map[string]any{"kind": "APIError", "code": api.Code,
                "httpStatus": api.StatusCode, "requestId": api.RequestID, "retryAfter": api.RetryAfter}
        } else if errors.As(err, &unknown) { detail["kind"] = "SubmissionUnknownError" }
        if saveErr := save("error.json", detail); saveErr != nil { return saveErr }
        return errors.New("inspect the saved attempt and History before retrying")
    }
    if err := save("result.json", result); err != nil { return err }
    if result.Status != "done" { return errors.New("response saved; inspect its status") }
    fmt.Printf("Saved: %s\nUsage: %+v\n", filepath.Join(directory, "result.json"), result.Usage)
    return nil
}
```

#### Chạy

```bash
go run ./cmd/archive runs/research-001
```



<a id="files"></a>

### Mong đợi tập tin

Thành công in đường dẫn và sử dụng kết quả đã lưu. result.json nên có status: done; Google Kết quả rồi. results[].organic[]. Một hệ thống hữu cơ rỗng là hợp lệ. Một báo cáo API hoặc lỗi giao thông được lưu error.json; intent.json Vẫn còn lại hồ sơ ban đầu.

#### Thành công trong nỗ lực

```text
runs/research-001/
  request.json # Nguồn, truy vấn và tham số
  intent.json # Cố gắng bắt đầu thời gian
  result.json # Đáp ứng đầy đủ, bao gồm kết quả và sử dụng
```


<a id="read"></a>

## 3. Đọc kết xuất đã lưu

Đọc result.json Để phân tích, tóm tắt và làm việc ở UI. Những lệnh này chỉ dùng tập tin cục bộ. Chạy lại việc tìm kiếm với cùng một thư mục dừng lại trước khi gọi đến mạng; nó không phối hợp các máy khác nhau hoặc phục hồi một trả lời máy chủ bị mất.

### Bash

#### Đọc ở địa phương

```bash
cat runs/research-001/result.json
```


### PowerShell

#### Đọc ở địa phương

```powershell
Get-Content -Raw -LiteralPath './runs/research-001/result.json'
```


### Go: đã gõ kết quả

Tạo cmd/read và lưu bộ giải mã ở đó. Nó đọc tập tin và in tiêu đề nguồn và URLs mà không tạo một khách hàng hay tạo ra một API yêu cầu.

#### cmd/read/main.go

```go
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
    flashdata "github.com/flashdatadev/flashdata-go"
)

func main() {
    filename := "runs/research-001/result.json"
    if len(os.Args) > 1 { filename = os.Args[1] }
    data, err := os.ReadFile(filename)
    if err != nil { log.Fatal(err) }
    var result flashdata.DataQueryResponse
    if err := json.Unmarshal(data, &result); err != nil { log.Fatal(err) }
    if result.Source != "google_search" || result.Status != "done" {
        log.Fatal("Expected a completed Google Search response")
    }
    pages, err := flashdata.DecodeResults[flashdata.GoogleSearchPayload](&result)
    if err != nil { log.Fatal(err) }
    for _, page := range pages {
        for _, hit := range page.Organic {
            if hit.Title != nil && hit.Link != nil { fmt.Println(*hit.Title, *hit.Link) }
        }
    }
    fmt.Printf("Original query credits: %g\n", result.Usage.Credits)
}
```

#### @ info/ rich

```bash
go run ./cmd/read runs/research-001/result.json
```


- [Tham số Google Search kết quả](https://flashdata.dev/vi/docs/sources/google_search/reference.md)
- [Định dạng kết quả chia sẻ](https://flashdata.dev/vi/docs/guides/response-formats/reference.md)

<a id="errors"></a>

## Hãy quyết định phải làm gì sau khi thất bại

| Những gì bạn có | Hành động tiếp theo |
| --- | --- |
| Thư mục tồn tại / EEXST | Kiểm tra hồ sơ của nó. Không có yêu cầu mới nào được gửi bằng nỗ lực này. |
| result.json, status: done | Đọc và xử lý phản ứng đã được cứu. Dùng lại nó làm biên nhận của điện gốc. |
| error.json có 401 / 403 / 402 | Sửa quyền truy cập, quyền truy cập nguồn hoặc số dư trước khi lên kế hoạch một nỗ lực mới. |
| 429 / retryAfter | Hãy chờ theo hướng dẫn và giảm mức yêu cầu. Xem lại việc thử đã thất bại trước khi chọn thư mục chạy mới. |
| Không biết phục tùng / mục đích chỉ / ghi thất bại | Công việc có thể đã được chấp nhận rồi. Giữ thư mục và thanh tra History hoặc một công việc đã biết ID Trước khi gửi một truy vấn khác. |

- [Yêu cầu lịch sử](https://flashdata.dev/app/jobs)
- [Những quyết định hồi phục](https://flashdata.dev/vi/docs/guides/agent-recovery/reference.md)

<a id="async"></a>

## Async Khách hàng và công việc nền

| Cần | Dùng |
| --- | --- |
| Giữ một vòng lặp sự kiện trả lời | Hạt SDKMột khách hàng đặc biệt, đang chờ điện thoại. Một truy vấn thời gian thực vẫn hoàn thành trong phản ứng HTTP của nó. |
| Tiếp tục sau khi tiến trình gọi thoát | Gửi một công việc nền một lần, lưu từ xa IDSau đó đọc địa vị và kết quả. |
| Chạy theo lịch | Sử dụng quyền truy cập của người sở hữu và các ứng dụng bền bỉ chạy các hồ sơ, hoặc các CLINhật ký chạy của chạy hiện tại. |

- [Async và luồng công việc](https://flashdata.dev/vi/docs/guides/async-batch/reference.md)
- [Tác vụ định kỳ](https://flashdata.dev/vi/docs/guides/recurring-tasks/reference.md)
