Upsert
curl --request PUT \
--url http://api.gu1.ai/entities/upsert \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": true
}
'import requests
url = "http://api.gu1.ai/entities/upsert"
payload = {
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.put(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'PUT',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
entity: {},
options: {},
'options.conflictResolution': {},
'options.deduplicationStrategy': {},
'options.createRelationships': true
})
};
fetch('http://api.gu1.ai/entities/upsert', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/entities/upsert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode([
'entity' => [
],
'options' => [
],
'options.conflictResolution' => [
],
'options.deduplicationStrategy' => [
],
'options.createRelationships' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/entities/upsert"
payload := strings.NewReader("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.put("http://api.gu1.ai/entities/upsert")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/entities/upsert")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Put.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}"
response = http.request(request)
puts response.read_body{
"success": true,
"action": "<string>",
"entity": {},
"previousEntity": {},
"confidence": 123,
"reasoning": "<string>",
"conflicts": [
{}
]
}Referência API
Upsert de uma entidade pessoa
Cria ou atualiza uma pessoa no gu1 com detecção de duplicatas sobre ID externo, identificação nacional, e-mail e telefone para evitar duplicidade KYC.
PUT
/
entities
/
upsert
Upsert
curl --request PUT \
--url http://api.gu1.ai/entities/upsert \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": true
}
'import requests
url = "http://api.gu1.ai/entities/upsert"
payload = {
"entity": {},
"options": {},
"options.conflictResolution": {},
"options.deduplicationStrategy": {},
"options.createRelationships": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.put(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'PUT',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
entity: {},
options: {},
'options.conflictResolution': {},
'options.deduplicationStrategy': {},
'options.createRelationships': true
})
};
fetch('http://api.gu1.ai/entities/upsert', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/entities/upsert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode([
'entity' => [
],
'options' => [
],
'options.conflictResolution' => [
],
'options.deduplicationStrategy' => [
],
'options.createRelationships' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/entities/upsert"
payload := strings.NewReader("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
req, _ := http.NewRequest("PUT", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.put("http://api.gu1.ai/entities/upsert")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/entities/upsert")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Put.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entity\": {},\n \"options\": {},\n \"options.conflictResolution\": {},\n \"options.deduplicationStrategy\": {},\n \"options.createRelationships\": true\n}"
response = http.request(request)
puts response.read_body{
"success": true,
"action": "<string>",
"entity": {},
"previousEntity": {},
"confidence": 123,
"reasoning": "<string>",
"conflicts": [
{}
]
}Visão Geral
O endpoint upsert cria inteligentemente uma nova pessoa ou atualiza uma existente com base em estratégias configuráveis de detecção de duplicatas. Ele lida automaticamente com conflitos e previne registros duplicados usando correspondência exata, correspondência difusa ou detecção de similaridade alimentada por IA.Endpoint
PUT http://api.gu1.ai/entities/upsert
Autenticação
Requer uma chave de API válida no cabeçalho de autorização:Authorization: Bearer YOUR_API_KEY
Corpo da Requisição
object
required
Os dados da pessoa (mesma estrutura do endpoint Criar Pessoa)
object
Opções de configuração para o comportamento do upsert
enum
Como lidar com conflitos quando uma pessoa existente é encontrada:
source_wins- Novos dados sobrescrevem dados existentestarget_wins- Mantém dados existentes, ignora novos dadosmanual_review- Sinaliza para revisão manual sem atualizarsmart_merge(padrão) - Mescla inteligentemente ambos os conjuntos de dados
enum
Estratégia para detectar pessoas duplicadas:
exact_match- Correspondência por externalId e taxId (insensível a maiúsculas/minúsculas)fuzzy_match- Correspondência de similaridade em nome e taxId (limite de 80%)ai_similarity- Detecção de similaridade semântica alimentada por IAhybrid(recomendado) - Correspondência exata com fallback difuso
boolean
default:"true"
Se deve criar automaticamente relacionamentos entre entidades
Resposta
boolean
Indica se a operação foi bem-sucedida
string
A ação realizada:
created ou updatedobject
O estado final da pessoa após o upsert
object
O estado da pessoa antes da atualização (null se recém-criada)
number
Pontuação de confiança (0-1) para a correspondência de detecção de duplicatas
string
Explicação de por que a pessoa foi criada/atualizada
array
Array de conflitos em nível de campo detectados durante a mesclagem (se houver)
Exemplos
Upsert Simples (Comportamento Padrão)
curl -X PUT http://api.gu1.ai/entities/upsert \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entity": {
"type": "person",
"externalId": "customer_12345",
"name": "María González",
"countryCode": "AR",
"taxId": "20-12345678-9",
"entityData": {
"person": {
"firstName": "María",
"lastName": "González",
"dateOfBirth": "1985-03-15",
"occupation": "Software Engineer",
"income": 85000
}
}
}
}'
const response = await fetch('http://api.gu1.ai/entities/upsert', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entity: {
type: 'person',
externalId: 'customer_12345',
name: 'María González',
countryCode: 'AR',
taxId: '20-12345678-9',
entityData: {
person: {
firstName: 'María',
lastName: 'González',
dateOfBirth: '1985-03-15',
occupation: 'Software Engineer',
income: 85000
}
}
}
})
});
const result = await response.json();
console.log(`Action: ${result.action}`); // 'created' ou 'updated'
console.log(`Confidence: ${result.confidence}`);
import requests
response = requests.put(
'http://api.gu1.ai/entities/upsert',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entity': {
'type': 'person',
'externalId': 'customer_12345',
'name': 'María González',
'countryCode': 'AR',
'taxId': '20-12345678-9',
'entityData': {
'person': {
'firstName': 'María',
'lastName': 'González',
'dateOfBirth': '1985-03-15',
'occupation': 'Software Engineer',
'income': 85000
}
}
}
}
)
result = response.json()
print(f"Action: {result['action']}")
print(f"Confidence: {result['confidence']}")
Upsert com Correspondência Difusa
curl -X PUT http://api.gu1.ai/entities/upsert \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entity": {
"type": "person",
"externalId": "customer_new_123",
"name": "Maria Gonzales",
"countryCode": "AR",
"taxId": "20-12345678-9",
"entityData": {
"person": {
"firstName": "Maria",
"lastName": "Gonzales"
}
}
},
"options": {
"deduplicationStrategy": "fuzzy_match",
"conflictResolution": "smart_merge"
}
}'
// Corresponderá "Maria Gonzales" com "María González" existente
// devido ao limite de similaridade de 80%+
const response = await fetch('http://api.gu1.ai/entities/upsert', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entity: {
type: 'person',
externalId: 'customer_new_123',
name: 'Maria Gonzales', // Pequena variação na ortografia
countryCode: 'AR',
taxId: '20-12345678-9',
entityData: {
person: {
firstName: 'Maria',
lastName: 'Gonzales'
}
}
},
options: {
deduplicationStrategy: 'fuzzy_match',
conflictResolution: 'smart_merge'
}
})
});
const result = await response.json();
console.log(`Matched with confidence: ${result.confidence}`);
console.log(`Reasoning: ${result.reasoning}`);
import requests
# Corresponderá "Maria Gonzales" com "María González" existente
response = requests.put(
'http://api.gu1.ai/entities/upsert',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entity': {
'type': 'person',
'externalId': 'customer_new_123',
'name': 'Maria Gonzales', # Pequena variação
'countryCode': 'AR',
'taxId': '20-12345678-9',
'entityData': {
'person': {
'firstName': 'Maria',
'lastName': 'Gonzales'
}
}
},
'options': {
'deduplicationStrategy': 'fuzzy_match',
'conflictResolution': 'smart_merge'
}
}
)
result = response.json()
print(f"Matched with confidence: {result['confidence']}")
print(f"Reasoning: {result['reasoning']}")
Exemplos de Resposta
Nova Pessoa Criada
{
"success": true,
"action": "created",
"entity": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"externalId": "customer_12345",
"type": "person",
"name": "María González",
...
},
"previousEntity": null,
"confidence": 1.0,
"reasoning": "No existing entity found matching criteria. Created new entity.",
"conflicts": []
}
Pessoa Existente Atualizada
{
"success": true,
"action": "updated",
"entity": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"externalId": "customer_12345",
"type": "person",
"name": "María González",
"entityData": {
"person": {
"income": 95000
}
},
...
},
"previousEntity": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"entityData": {
"person": {
"income": 85000
}
},
...
},
"confidence": 1.0,
"reasoning": "Exact match found on externalId. Updated existing entity with smart merge.",
"conflicts": [
{
"field": "entityData.person.income",
"oldValue": 85000,
"newValue": 95000,
"resolution": "source_wins"
}
]
}
Casos de Uso
Importação de Dados do CRM
// Importar dados de clientes do CRM, evitando duplicatas
async function importCustomer(crmData) {
const response = await fetch('http://api.gu1.ai/entities/upsert', {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entity: {
type: 'person',
externalId: crmData.customerId,
name: crmData.fullName,
countryCode: crmData.country,
taxId: crmData.taxId,
entityData: {
person: {
firstName: crmData.firstName,
lastName: crmData.lastName,
income: crmData.annualIncome
}
},
attributes: {
source: 'crm_import',
importDate: new Date().toISOString()
}
},
options: {
deduplicationStrategy: 'hybrid',
conflictResolution: 'smart_merge'
}
})
});
return response.json();
}
Enriquecimento Progressivo de Dados
def enrich_person_data(external_id, new_data):
"""Adicionar dados progressivamente à pessoa conforme ficam disponíveis"""
response = requests.put(
'http://api.gu1.ai/entities/upsert',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entity': {
'type': 'person',
'externalId': external_id,
'name': new_data.get('name'),
'countryCode': new_data.get('country'),
'entityData': new_data.get('details', {}),
'attributes': new_data.get('attributes', {})
},
'options': {
'deduplicationStrategy': 'exact_match',
'conflictResolution': 'smart_merge' # Mesclar novo com existente
}
}
)
result = response.json()
if result['action'] == 'updated':
print(f"Enriched existing person with new data")
return result
Melhores Práticas
-
Escolha a Estratégia Certa:
exact_matchpara dados limpos e estruturados com IDs confiáveisfuzzy_matchpara dados inseridos pelo usuário com possíveis erros de digitaçãohybridpara a maioria dos cenários de produção
-
Lidar com Conflitos Graciosamente:
- Use
smart_mergepara resolução automática - Use
manual_reviewpara dados críticos - Verifique o array
conflictsna resposta para mudanças importantes
- Use
-
Monitorar Pontuações de Confiança:
- Pontuações abaixo de 0.7 podem indicar correspondências fracas
- Registre atualizações de baixa confiança para revisão
Respostas de Erro
400 Bad Request
{
"error": "Invalid tax ID format for country"
}
500 Internal Server Error
{
"error": "Failed to upsert entity"
}
Próximos Passos
- Listar Pessoas - Consultar pessoas upsertadas
- Atualizar Pessoa - Fazer atualizações direcionadas
- Obter Pessoa - Recuperar detalhes completos da pessoa
Was this page helpful?