Continuare una conversazione

Porta avanti un dialogo a più turni includendo tutta la cronologia dei messaggi.

Come funziona

  1. Usa lo stesso id per tutti i messaggi della conversazione
  2. Includi tutti i messaggi precedenti, in ordine
  3. Aggiungi il messaggio nuovo in fondo

Esempio

Turno 1: prima domanda

Shell
curl -N -X POST BOX_URL/api/ai/chat \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "conversation-123",
    "messages": [
      {"role": "user", "content": "What is the capital of France?"}
    ],
    "boxAddress": "BOX_URL"
  }'

Risposta: «La capitale della Francia è Parigi.»

Turno 2: domanda di approfondimento

Includi lo scambio precedente:

Shell
curl -N -X POST BOX_URL/api/ai/chat \
  -H "x-api-key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "id": "conversation-123",
    "messages": [
      {"role": "user", "content": "What is the capital of France?"},
      {"role": "assistant", "content": "The capital of France is Paris."},
      {"role": "user", "content": "What is its population?"}
    ],
    "boxAddress": "BOX_URL"
  }'

L’AI capisce che «sua» si riferisce a Parigi perché ha il contesto.

Turno 3: ancora un approfondimento

JSON
{
  "id": "conversation-123",
  "messages": [
    {"role": "user", "content": "What is the capital of France?"},
    {"role": "assistant", "content": "The capital of France is Paris."},
    {"role": "user", "content": "What is its population?"},
    {"role": "assistant", "content": "Paris has a population of about 2.1 million..."},
    {"role": "user", "content": "What about the metro area?"}
  ],
  "boxAddress": "BOX_URL"
}

Esempio in JavaScript

conversation.js
class Conversation {
  constructor(apiKey, boxAddress = 'https://your-box.intelligencebox.it') {
    this.id = 'conv-' + Date.now();
    this.messages = [];
    this.apiKey = apiKey;
    this.boxAddress = boxAddress;
  }

  async send(message) {
    // Add user message
    this.messages.push({ role: 'user', content: message });

    const response = await fetch(`${this.boxAddress}/api/ai/chat`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': this.apiKey
      },
      body: JSON.stringify({
        id: this.id,
        messages: this.messages,
        boxAddress: this.boxAddress
      })
    });

    // Parse SSE and collect response
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let assistantResponse = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      for (const line of decoder.decode(value).split('\n')) {
        if (line.startsWith('data: ')) {
          try {
            const data = JSON.parse(line.slice(6));
            if (data.type === 'text-delta') {
              assistantResponse += data.textDelta;
            }
          } catch (e) {}
        }
      }
    }

    // Add assistant response to history
    this.messages.push({ role: 'assistant', content: assistantResponse });

    return assistantResponse;
  }
}

// Usage
const chat = new Conversation('YOUR_API_KEY');

const r1 = await chat.send('What is the capital of France?');
console.log(r1); // "The capital of France is Paris."

const r2 = await chat.send('What is its population?');
console.log(r2); // "Paris has a population of about 2.1 million..."

const r3 = await chat.send('Compare it to London');
console.log(r3); // AI knows we're comparing Paris to London

Con un assistente

Puoi proseguire le conversazioni anche con gli assistenti:

JSON
{
  "id": "conversation-123",
  "messages": [
    {"role": "user", "content": "Analyze my sales data"},
    {"role": "assistant", "content": "Based on your documents, sales increased by 15%..."},
    {"role": "user", "content": "What about Q4 specifically?"}
  ],
  "boxAddress": "BOX_URL",
  "assistantId": "your-assistant-id",
  "vector": ["your-folder-id"]
}

Consigli

  • Stesso ID: usa sempre lo stesso id per l’intera conversazione
  • Cronologia completa: includi tutti i messaggi ogni volta
  • L’ordine conta: i messaggi devono essere in ordine cronologico
  • Accorcia le chat lunghe: nelle conversazioni molto lunghe conviene riassumere i messaggi più vecchi
Continuare una conversazione | IntelligenceBox