Exemplos de Uso

Exemplos práticos e casos de uso da API Arkangel AI

por Arkangel AI Team•1 min de leitura

Explore exemplos práticos de como integrar a API Arkangel AI em suas aplicações.

Consulta Médica Simples

O caso de uso mais básico: fazer uma pergunta e obter uma resposta.

async function askMedicalQuestion(question) {
  const response = await fetch('https://api.arkangelai.com/v1/chat', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sua_chave_api',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: question,
      language: 'pt'
    })
  });

  const data = await response.json();
  return data.message;
}

// Uso
const resposta = await askMedicalQuestion(
  'Quais são os efeitos colaterais comuns do ibuprofeno?'
);
console.log(resposta);

Chat com Histórico

Mantenha uma conversa com contexto completo.

class MedicalChat {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.conversationId = null;
  }

  async sendMessage(message) {
    const body = { message };

    if (this.conversationId) {
      body.conversation_id = this.conversationId;
    }

    const response = await fetch('https://api.arkangelai.com/v1/chat', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    });

    const data = await response.json();
    this.conversationId = data.conversation_id;

    return data.message;
  }

  reset() {
    this.conversationId = null;
  }
}

// Uso
const chat = new MedicalChat('sua_chave_api');

await chat.sendMessage('O que é hipertensão?');
await chat.sendMessage('Quais são seus sintomas?');
await chat.sendMessage('Como pode ser prevenida?');

Análise de Documentos

Faça upload de um documento médico e faça perguntas sobre ele.

async function analyzeDocument(file, question) {
  // 1. Fazer upload do arquivo
  const formData = new FormData();
  formData.append('file', file);
  formData.append('purpose', 'analysis');

  const uploadResponse = await fetch('https://api.arkangelai.com/v1/files', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sua_chave_api'
    },
    body: formData
  });

  const uploadData = await uploadResponse.json();

  // 2. Consultar com o arquivo
  const chatResponse = await fetch('https://api.arkangelai.com/v1/chat', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sua_chave_api',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      message: question,
      file_ids: [uploadData.file_id]
    })
  });

  return chatResponse.json();
}

// Uso
const resultado = await analyzeDocument(
  pdfFile,
  'Resuma as principais descobertas deste estudo'
);

Streaming em Tempo Real

Exiba respostas conforme são geradas.

async function streamResponse(message, onChunk) {
  const response = await fetch('https://api.arkangelai.com/v1/chat/stream', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sua_chave_api',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ message })
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

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

    const chunk = decoder.decode(value);
    onChunk(chunk);
  }
}

// Uso com React
function ChatComponent() {
  const [response, setResponse] = useState('');

  const handleSubmit = async (question) => {
    setResponse('');
    await streamResponse(question, (chunk) => {
      setResponse(prev => prev + chunk);
    });
  };

  return <div>{response}</div>;
}

Integração Python

Exemplo completo usando Python.

import requests
from typing import Optional

class ArkangelClient:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = 'https://api.arkangelai.com/v1'
        self.conversation_id: Optional[str] = None

    def _headers(self):
        return {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json'
        }

    def chat(self, message: str, new_conversation: bool = False) -> dict:
        if new_conversation:
            self.conversation_id = None

        payload = {'message': message}
        if self.conversation_id:
            payload['conversation_id'] = self.conversation_id

        response = requests.post(
            f'{self.base_url}/chat',
            headers=self._headers(),
            json=payload
        )
        response.raise_for_status()

        data = response.json()
        self.conversation_id = data.get('conversation_id')
        return data

    def upload_file(self, file_path: str) -> str:
        with open(file_path, 'rb') as f:
            response = requests.post(
                f'{self.base_url}/files',
                headers={'Authorization': f'Bearer {self.api_key}'},
                files={'file': f},
                data={'purpose': 'analysis'}
            )
        response.raise_for_status()
        return response.json()['file_id']

    def get_usage(self) -> dict:
        response = requests.get(
            f'{self.base_url}/usage',
            headers=self._headers()
        )
        response.raise_for_status()
        return response.json()


# Uso
client = ArkangelClient('sua_chave_api')

# Chat simples
resposta = client.chat('O que é colesterol?')
print(resposta['message'])

# Conversa contínua
client.chat('Quais são os valores normais?')
client.chat('Como pode ser reduzido?')

# Ver uso
uso = client.get_usage()
print(f"Solicitações hoje: {uso['usage']['total_requests']}")

Tratamento de Erros

Implemente tratamento robusto de erros.

async function safeApiCall(endpoint, options) {
  const maxRetries = 3;
  let lastError;

  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(endpoint, options);

      if (response.status === 429) {
        // Limite atingido - aguardar e tentar novamente
        const retryAfter = response.headers.get('Retry-After') || 60;
        await sleep(retryAfter * 1000);
        continue;
      }

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.message || 'Erro da API');
      }

      return response.json();
    } catch (error) {
      lastError = error;
      if (i < maxRetries - 1) {
        await sleep(1000 * (i + 1)); // Backoff exponencial
      }
    }
  }

  throw lastError;
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Próximos Passos