문서 둘러보기
시작하기
각 시도의 기록을 유지하고 다른 API 통화없이 저장된 결과를 읽으십시오.
이 페이지의 내용
시작하기 전에
프로젝트를 사용하여 SDK 및 FLASHDATA_API_KEY를 SDK Quickstart에서 설치했습니다. 아래 언어 선택. 각 새로운 실행 디렉토리는 하나의 의도 된 검색을 나타냅니다; 어떤 요청을 만들기 전에 기존 디렉토리를 재사용합니다.
1. 액세스 및 현재 비용 확인
SDK에 맞는 확인 코드를 저장하고 실행하세요. 권한, 잔액 및 Google Search 한 번의 가격을 읽습니다. Access check passed가 표시된 뒤에만 진행하세요. 이 확인은 유료 쿼리를 보내거나 크레딧을 예약하지 않습니다.
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).venv/bin/python check_access.py.\.venv\Scripts\python.exe check_access.pyimport { 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;
}node check-access.mjscmd/check를 생성하고이 파일을 저장하십시오.
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.")
}go run ./cmd/check2. 새로운 출력 디렉토리로 실행
체크 패스 후이 프로그램 중 하나를 실행합니다. 제출하기 전에 디렉토리를 작성하고 요청을 기록 한 다음 응답을 저장합니다. 실패에 디렉토리를 유지: 삭제하거나 새로운 것을 선택하면 다른 청구 가능한 쿼리를 허용.
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).venv/bin/python archive_search.py runs/research-001.\.venv\Scripts\python.exe archive_search.py runs/research-001JavaScript 또는 TypeScript 프로젝트 중 하나에서 이 노드 ESM 프로그램을 저장하십시오. @flashdata-dev/sdk 패키지를 동시에 설치합니다.
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;
}node archive-search.mjs runs/research-001cmd/archive를 작성하여 이 항목 포인트는 Quickstart 프로그램에서 분리됩니다.
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
}go run ./cmd/archive runs/research-001예상된 파일
성공은 저장된 결과 경로와 사용법을 인쇄합니다. result.json는 status: done가 있어야 합니다; Google 결과는 results[].organic[]에 있습니다. 빈 유기 배열은 유효합니다. API 또는 운송 오류가 error.json에 저장됩니다. intent.json는 원래 사전 제출 기록을 유지합니다.
runs/research-001/
request.json # 소스, 쿼리 및 매개 변수
intent.json # 시작 시간
result.json # 전체 응답, 결과 및 사용 포함3. 저장된 산출을 읽으십시오
파싱, summaries 및 UI 작업을 위해 result.json를 읽으십시오. 이 명령은 로컬 파일만 사용합니다. 네트워크 호출 전에 동일한 디렉토리의 검색을 다시 실행; 그것은 다른 기계를 조정하거나 손실 서버 응답을 복구하지 않습니다.
cat runs/research-001/result.jsonGet-Content -Raw -LiteralPath './runs/research-001/result.json'cmd/read를 생성하고 이 디코더를 저장하십시오. 클라이언트를 구성하거나 API 요청을 작성하지 않고 파일 및 인쇄 소스 제목 및 URLs를 읽습니다.
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)
}go run ./cmd/read runs/research-001/result.json실패 후 무엇을 할 것인가?
| 당신은 무엇을 | 다음 작업 |
|---|---|
| 기존 디렉토리 / EEXIST | 파일 검사. 이 시도에 의해 새로운 쿼리가 전송되지 않았습니다. |
| result.json, status: done | 저장된 응답을 읽고 처리하십시오. 원래 충전의 영수증으로 사용. |
| error.json와 401/403/402 | 새로운 시도를 계획하기 전에 액세스, 소스 권한 또는 균형을 수정합니다. |
| 429 / retryAfter | 지시되고 요청 속도를 감소시키십시오. 새로운 실행 디렉토리를 선택하기 전에 실패한 시도를 검토하십시오. |
| 알 수없는 제출 / 의도 만 / 쓰기 실패 | 작업은 이미 받아들일 수 있습니다. 디렉토리를 유지하고 다른 쿼리를 보내기 전에 History 또는 알려진 작업 ID를 검사합니다. |
Async 클라이언트 및 배경 작업
| 지원하다 | 제품 정보 |
|---|---|
| 이벤트 루프 응답 유지 | SDK의 동기화 클라이언트 / 통화를 기다립니다. 실시간 쿼리는 여전히 HTTP 응답에 완료됩니다. |
| 호출 프로세스 종료 후 재량 | 한 번의 배경 작업을 제출하면 원격 ID를 저장하고 상태와 결과를 읽습니다. |
| 자주 묻는 질문 | 소유자 액세스 및 내구성 응용 프로그램 실행 기록, 또는 CLI의 기존 실행 저널. |