ITSkillsCenter
Intelligence Artificielle

Claude API avec TypeScript : premier agent fonctionnel

3 دقائق للقراءة
Miniature - Claude API avec TypeScript : premier agent fonctionnel

Ce que vous saurez faire à la fin

  1. Installer le SDK Anthropic TypeScript
  2. Créer un agent avec tool_use
  3. Valider les entrées avec Zod
  4. Streaming et prompt caching
  5. Déployer en production

Étape 1 — Installation

npm install @anthropic-ai/sdk@0.32.1 dotenv zod
npm install -D typescript @types/node tsx

Étape 2 — Premier appel

import Anthropic from "@anthropic-ai/sdk";
import "dotenv/config";

const client = new Anthropic();

const msg = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  messages: [{ role: "user", content: "Plan SQL 5 modules" }],
});

const text = msg.content
  .filter((b): b is Anthropic.TextBlock => b.type === "text")
  .map(b => b.text).join("");
console.log(text);

Étape 3 — Agent avec tool_use

const tools: Anthropic.Tool[] = [{
  name: "recherche_fichier",
  description: "Cherche un fichier par pattern",
  input_schema: {
    type: "object",
    properties: { pattern: { type: "string" } },
    required: ["pattern"],
  },
}];

async function agent(demande: string) {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: demande }];
  
  for (let tour = 0; tour < 10; tour++) {
    const r = await client.messages.create({
      model: "claude-sonnet-4-6",
      max_tokens: 2048,
      tools,
      messages,
    });
    
    if (r.stop_reason === "end_turn") {
      return r.content.filter((b: any) => b.type === "text").map((b: any) => b.text).join("");
    }
    
    messages.push({ role: "assistant", content: r.content });
    const toolResults: any[] = [];
    for (const b of r.content) {
      if (b.type === "tool_use") {
        const result = { files: ["src/index.ts"] };
        toolResults.push({ type: "tool_result", tool_use_id: b.id, content: JSON.stringify(result) });
      }
    }
    messages.push({ role: "user", content: toolResults });
  }
  throw new Error("trop de tours");
}

Étape 4 — Validation Zod

import { z } from "zod";
const SchemaRecherche = z.object({ pattern: z.string().min(1).max(100) });

function execRecherche(raw: unknown) {
  const { pattern } = SchemaRecherche.parse(raw);
  return { files: [] };
}

Étape 5 — Streaming Node

const stream = await client.messages.stream({
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  messages: [{ role: "user", content: "200 mots sur Dakar" }],
});

for await (const chunk of stream) {
  if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
    process.stdout.write(chunk.delta.text);
  }
}

Étape 6 — Prompt caching

const r = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  system: [{
    type: "text",
    text: GROS_SYSTEM,  // > 1024 tokens requis
    cache_control: { type: "ephemeral" },
  }],
  messages: [{ role: "user", content: "Résume" }],
});
console.log("cache_read:", r.usage.cache_read_input_tokens);

Étape 7 — Retries

async function withRetry<T>(fn: () => Promise<T>, max = 3): Promise<T> {
  for (let i = 0; i < max; i++) {
    try { return await fn(); }
    catch (e: any) {
      if (e.status === 429 || e.status >= 500) {
        await new Promise(r => setTimeout(r, 2 ** i * 1000));
        continue;
      }
      throw e;
    }
  }
  throw new Error("max retries");
}

Étape 8 — Config production

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY!,
  maxRetries: 3,
  timeout: 60_000,
});

Étape 9 — Logging

import pino from "pino";
const log = pino();
log.info({
  input: r.usage.input_tokens,
  output: r.usage.output_tokens,
  cache_read: r.usage.cache_read_input_tokens ?? 0,
}, "api_call");

Étape 10 — Checklist

✓ Clé API en env var
✓ Timeout et maxRetries configurés
✓ withRetry sur 429 et 5xx
✓ Prompt caching sur system stable
✓ Zod pour validation inputs
✓ Logging structuré des coûts
Besoin d'un site web ?

Confiez-nous la Création de Votre Site Web

Site vitrine, e-commerce ou application web — nous transformons votre vision en réalité digitale. Accompagnement personnalisé de A à Z.

À partir de 250.000 FCFA
Parlons de Votre Projet
Publicité