synapse

package module
v0.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 20, 2026 License: MIT Imports: 11 Imported by: 0

README

Synapse Go SDK

Client oficial em Go para a API Synapse.


Instalação

go get github.com/WonitTecnologia/synapse

Início rápido

import "github.com/WonitTecnologia/synapse"

client, err := synapse.NewClient("seu-token", nil)
if err != nil {
    log.Fatal(err)
}

Configuração

NewClient aceita um token obrigatório e um *Options opcional.

client, err := synapse.NewClient("seu-token", &synapse.Options{
    BaseURL: "https://staging.synapse.example.com", // padrão: https://synapse.wonit.net.br
    Timeout: 15 * time.Second,                      // padrão: 30s
})
Campo Tipo Descrição
BaseURL string Sobrescreve a URL base da API (staging, self-hosted…)
Timeout time.Duration Timeout por requisição HTTP. Padrão: 30s

Domínios

Campo Interface Endpoints cobertos
client.Auth AuthCase Login, logout, OTP, reset de senha, API tokens
client.User UserCase CRUD de usuários
client.Tenant TenantCase CRUD de tenants
client.Provider ProviderCase Listagem de providers do catálogo
client.Service ServiceCase Listagem de services do catálogo
client.Google GoogleCase Integração Google Vision AI (OCR)
client.OpenAI OpenAICase Chat, análise de imagem, transcrição de áudio
client.Chatvolt ChatvoltCase Query a agentes Chatvolt

Auth

Login
resp, err := client.Auth.Login(ctx, synapse.LoginRequest{
    Email:    "usuario@empresa.com",
    Password: "senha123",
})

fmt.Println(resp.Token)
fmt.Println(resp.User.Name)
Healthcheck (validar token)
resp, err := client.Auth.Healthcheck(ctx)
fmt.Println(resp.User.Email)
Logout
err := client.Auth.Logout(ctx, "token-a-revogar")
Solicitar OTP
err := client.Auth.RequestOTP(ctx, synapse.OTPRequest{
    Email: "usuario@empresa.com",
})
Resetar senha com OTP
err := client.Auth.ResetPassword(ctx, synapse.OTPResetPasswordRequest{
    Email:    "usuario@empresa.com",
    OTP:      "123456",
    Password: "novaSenha@123",
})
API Tokens
// Criar
token, err := client.Auth.CreateAPIToken(ctx, synapse.ApiTokenCreateRequest{
    Name:        "Integração CI",
    Description: "Token para pipeline de deploy",
    ExpireAt:    "2026-12-31T00:00:00Z", // opcional
})
fmt.Println(token.Token)

// Listar
list, err := client.Auth.ListAPITokens(ctx, 1, 20)
for _, t := range list.APITokens {
    fmt.Println(t.Name, t.ExpireAt)
}

User

// Buscar por UUID ou email
user, err := client.User.Get(ctx, "uuid-ou-email")

// Listar
users, err := client.User.List(ctx, synapse.ListUsersParams{
    Page:             1,
    Size:             20,
    TenantIdentifier: "uuid-do-tenant", // apenas SystemAdmin
})

// Criar  (identifier = UUID ou documento do tenant)
user, err := client.User.Create(ctx, "uuid-do-tenant", synapse.CreateUserRequestDto{
    Name:     "João Silva",
    Email:    "joao@empresa.com",
    Password: "senha@123",
    Role:     synapse.UserRoleTenantUser,
})

// Atualizar
user, err := client.User.Update(ctx, "uuid-do-usuario", synapse.UpdateUserRequestDto{
    Name: "João Silva Jr.",
})

// Deletar
err := client.User.Delete(ctx, "uuid-ou-email")
Roles disponíveis
Constante Valor
synapse.UserRoleSystemAdmin SYSTEM_ADMIN
synapse.UserRoleTenantAdmin TENANT_ADMIN
synapse.UserRoleTenantUser TENANT_USER

Tenant

// Buscar por UUID ou documento (CNPJ/CPF)
tenant, err := client.Tenant.Get(ctx, "uuid", "")
tenant, err := client.Tenant.Get(ctx, "", "12345678000199")

// Listar
tenants, err := client.Tenant.List(ctx, 1, 10)

// Criar
tenant, err := client.Tenant.Create(ctx, synapse.CreateTenantRequestDto{
    Name:     "Empresa XPTO",
    Document: "12345678000199",
})

// Atualizar
live := true
tenant, err := client.Tenant.Update(ctx, "uuid-do-tenant", synapse.UpdateTenantRequestDto{
    Name: "Empresa XPTO Ltda.",
    Live: &live,
})

// Deletar
err := client.Tenant.Delete(ctx, "uuid-do-tenant", "")

// Providers
provider, err := client.Provider.Get(ctx, "uuid-do-provider")
providers, err := client.Provider.List(ctx, 1, 20)

// Services
service, err := client.Service.Get(ctx, "uuid-do-service")
services, err := client.Service.List(ctx, 1, 20)

Google Vision AI

Configurar integração
err := client.Google.Configure(ctx, synapse.ConfigureGoogleRequest{
    Credentials: synapse.VisionAICredentialsDTO{Token: "sua-api-key-google"},
    IsActive:    true,
})
OCR (extração de texto)
imageBytes, _ := os.ReadFile("nota_fiscal.jpg")

result, err := client.Google.VisionOCR(ctx, "nota_fiscal.jpg", imageBytes)
fmt.Println(result.Response)

Formatos aceitos: png, jpg, jpeg, webp.


OpenAI

Configurar integração
err := client.OpenAI.Configure(ctx, synapse.ConfigureOpenAIRequest{
    Credentials: synapse.OpenAICredentialsDTO{Token: "sk-..."},
    Settings: synapse.OpenAISettingsDTO{
        Model:       synapse.OpenAIModelGPT4o,
        Temperature: 0.7,
    },
    IsActive: true,
})
Modelos disponíveis
Constante Modelo
synapse.OpenAIModelGPT4oMini gpt-4o-mini
synapse.OpenAIModelGPT4o gpt-4o
synapse.OpenAIModelGPT4_1 gpt-4.1
synapse.OpenAIModelGPT4_1Mini gpt-4.1-mini
synapse.OpenAIModelO4Mini o4-mini
Chat Completion
reply, err := client.OpenAI.Chat(ctx, synapse.ChatCompletionRequest{
    Prompt: "Resuma este contrato em 3 pontos.",
})
fmt.Println(reply.Response)
Análise de imagem
imageBytes, _ := os.ReadFile("diagrama.png")

result, err := client.OpenAI.AnalyzeImage(ctx, "diagrama.png", imageBytes, "Descreva o que está nesta imagem.")
fmt.Println(result.Response)
Transcrição de áudio
audioBytes, _ := os.ReadFile("reuniao.mp3")

result, err := client.OpenAI.TranscribeAudio(ctx, synapse.TranscribeAudioRequest{
    FileName: "reuniao.mp3",
    Content:  audioBytes,
    Model:    "whisper-1",    // whisper-1 | gpt-4o-transcribe | gpt-4o-mini-transcribe
    Language: "pt",           // opcional
    Prompt:   "",             // opcional: contexto para melhorar a transcrição
})
fmt.Println(result.Response)

Chatvolt

Configurar integração
err := client.Chatvolt.Configure(ctx, synapse.ConfigureChatvoltRequest{
    Credentials: synapse.ChatvoltCredentialsDTO{Token: "seu-token-chatvolt"},
    IsActive:    true,
})
Query a agente
// Nova conversa
resp, err := client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{
    AgentID: "id-do-agente",
    Query:   "Qual o status do meu pedido #1234?",
})
fmt.Println(resp.Answer)
fmt.Println(resp.ConversationID) // guarde para continuar o contexto

// Continuar conversa existente
resp, err = client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{
    AgentID:        "id-do-agente",
    ConversationID: resp.ConversationID,
    Query:          "E qual a previsão de entrega?",
})
Enviar dados de contato
resp, err := client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{
    AgentID: "id-do-agente",
    Query:   "Preciso de suporte.",
    Contact: &synapse.ChatvoltContact{
        Email:     "cliente@email.com",
        FirstName: "Maria",
        LastName:  "Souza",
    },
})

Tratamento de erros

Verificar tipo de erro com sentinels

Use errors.Is para identificar a categoria do erro sem precisar inspecionar o payload:

resp, err := client.Auth.Login(ctx, req)
if err != nil {
    switch {
    case errors.Is(err, synapse.ErrUnauthorized):
        // 401 — credenciais inválidas ou token expirado
    case errors.Is(err, synapse.ErrForbidden):
        // 403 — sem permissão para este recurso
    case errors.Is(err, synapse.ErrNotFound):
        // 404 — recurso não encontrado
    case errors.Is(err, synapse.ErrConflict):
        // 409 — duplicidade (ex: email já em uso)
    case errors.Is(err, synapse.ErrBadRequest):
        // 400 — parâmetros inválidos
    case errors.Is(err, synapse.ErrBadGateway):
        // 502 — erro no provedor externo (OpenAI, Google…)
    case errors.Is(err, synapse.ErrInternalServer):
        // 500 — erro interno da API
    default:
        // erro de rede, timeout, etc.
    }
}
Inspecionar payload completo da API

Use synapse.AsAPIError quando precisar dos detalhes (trace_id, causes):

if apiErr, ok := synapse.AsAPIError(err); ok {
    fmt.Println("HTTP status:", apiErr.StatusCode)
    fmt.Println("Trace ID:",    apiErr.TraceID)
    fmt.Println("Mensagem:",    apiErr.Message)

    for _, cause := range apiErr.Causes {
        fmt.Printf("  campo %q: %s\n", cause.Field, cause.Message)
    }
}
Sentinels disponíveis
Sentinel HTTP Quando ocorre
synapse.ErrInvalidToken Token vazio ao criar o client
synapse.ErrUnauthorized 401 Token inválido ou expirado
synapse.ErrForbidden 403 Sem permissão para o recurso
synapse.ErrNotFound 404 Recurso não encontrado
synapse.ErrConflict 409 Duplicidade (email, documento, token…)
synapse.ErrBadRequest 400 Parâmetros inválidos
synapse.ErrInternalServer 500 Erro interno da API
synapse.ErrBadGateway 502 Falha no provedor externo
synapse.ErrIntegrationNotConfigured 409 Integração não configurada para o tenant

Exemplo completo

package main

import (
    "context"
    "errors"
    "fmt"
    "log"
    "os"
    "time"

    "github.com/WonitTecnologia/synapse"
)

func main() {
    client, err := synapse.NewClient(os.Getenv("SYNAPSE_TOKEN"), &synapse.Options{
        Timeout: 20 * time.Second,
    })
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // Validar token
    me, err := client.Auth.Healthcheck(ctx)
    if err != nil {
        if errors.Is(err, synapse.ErrUnauthorized) {
            log.Fatal("token inválido ou expirado")
        }
        log.Fatal(err)
    }
    fmt.Printf("Logado como: %s (%s)\n", me.User.Name, me.User.Role)

    // Transcrever um áudio
    audio, _ := os.ReadFile("reuniao.mp3")
    transcription, err := client.OpenAI.TranscribeAudio(ctx, synapse.TranscribeAudioRequest{
        FileName: "reuniao.mp3",
        Content:  audio,
        Model:    "whisper-1",
        Language: "pt",
    })
    if err != nil {
        if apiErr, ok := synapse.AsAPIError(err); ok {
            log.Fatalf("erro da API [trace=%s]: %s", apiErr.TraceID, apiErr.Message)
        }
        log.Fatal(err)
    }
    fmt.Println("Transcrição:", transcription.Response)
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidToken             = errors.New("synapse: token cannot be empty")
	ErrUnauthorized             = errors.New("synapse: unauthorized — invalid or missing token")
	ErrForbidden                = errors.New("synapse: forbidden — insufficient permissions")
	ErrNotFound                 = errors.New("synapse: resource not found")
	ErrConflict                 = errors.New("synapse: conflict — resource already exists or duplicate")
	ErrBadRequest               = errors.New("synapse: bad request — invalid parameters")
	ErrInternalServer           = errors.New("synapse: internal server error")
	ErrBadGateway               = errors.New("synapse: bad gateway — upstream provider error")
	ErrIntegrationNotConfigured = errors.New("synapse: integration not configured for this tenant")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	// StatusCode is the HTTP status returned by the API.
	StatusCode int `json:"-"`

	// Code mirrors the numeric code in the response body.
	Code int `json:"code"`

	// Err is the short error label from the response body.
	Err string `json:"error"`

	// Message is the human-readable description from the response body.
	Message string `json:"message"`

	// TraceID is the trace identifier returned by the API for debugging.
	TraceID string `json:"trace_id"`

	// Causes holds field-level validation errors when applicable.
	Causes []RestErrCause `json:"causes"`
}

APIError represents an error response from the Synapse API. It carries the full response payload and wraps a typed sentinel error so callers can use errors.Is for control flow.

Example:

_, err := client.Auth.Login(ctx, req)
if errors.Is(err, synapse.ErrUnauthorized) { ... }

if apiErr, ok := synapse.AsAPIError(err); ok {
    fmt.Println(apiErr.TraceID, apiErr.Causes)
}

func AsAPIError

func AsAPIError(err error) (*APIError, bool)

AsAPIError unwraps err into *APIError and reports whether it succeeded. Use this to inspect the full API error payload (causes, trace_id, etc.).

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap maps the HTTP status code to the appropriate sentinel error, enabling errors.Is checks against the package-level sentinels.

type AnalyzeImageResponse

type AnalyzeImageResponse struct {
	Response string `json:"response"`
}

AnalyzeImageResponse is returned by both OpenAI and Google Vision image endpoints.

type ApiTokenCreateRequest

type ApiTokenCreateRequest struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	// ExpireAt is optional; if omitted the server sets a default expiry.
	ExpireAt string `json:"expire_at,omitempty"`
}

ApiTokenCreateRequest is the body for creating an API token.

type ApiTokenCreateResponse

type ApiTokenCreateResponse struct {
	UUID        string `json:"uuid"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Token       string `json:"token"`
	TenantUUID  string `json:"tenant_uuid"`
	UserUUID    string `json:"user_uuid"`
	ExpireAt    string `json:"expire_at"`
	CreatedAt   string `json:"create_at"`
}

ApiTokenCreateResponse describes a created or listed API token.

type AuthCase

type AuthCase interface {
	// Login authenticates a user with email and password and returns an access token.
	Login(ctx context.Context, req LoginRequest) (*LoginResponse, error)

	// Logout revokes the given access token.
	Logout(ctx context.Context, token string) error

	// Healthcheck validates the current token and returns the logged-in user's data.
	Healthcheck(ctx context.Context) (*LoginResponse, error)

	// RequestOTP sends a one-time password to the given email address.
	RequestOTP(ctx context.Context, req OTPRequest) error

	// ResetPassword validates the OTP and replaces the user's password.
	ResetPassword(ctx context.Context, req OTPResetPasswordRequest) error

	// ListAPITokens returns all API tokens linked to the authenticated user.
	// Use page=0 and pageSize=0 to rely on server defaults.
	ListAPITokens(ctx context.Context, page, pageSize int) (*ListApiTokensResponse, error)

	// CreateAPIToken creates a new API token for the authenticated user.
	CreateAPIToken(ctx context.Context, req ApiTokenCreateRequest) (*ApiTokenCreateResponse, error)
}

AuthCase provides all authentication-related operations against the Synapse API.

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Prompt string `json:"prompt"`
}

ChatCompletionRequest is the body for a chat completion call.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	Response string `json:"response"`
}

ChatCompletionResponse is the response from a chat completion call.

type ChatvoltAgentItem added in v0.0.4

type ChatvoltAgentItem struct {
	ID          string                  `json:"id"`
	Name        string                  `json:"name"`
	IconUrl     *string                 `json:"iconUrl,omitempty"`
	Description string                  `json:"description"`
	ModelName   string                  `json:"modelName"`
	Visibility  ChatvoltAgentVisibility `json:"visibility"`
}

ChatvoltAgentItem describes a single Chatvolt agent returned by the catalog.

type ChatvoltAgentQueryRequest

type ChatvoltAgentQueryRequest struct {
	AgentID string `json:"agentId"`
	Query   string `json:"query"`
	// ConversationID keeps context across turns; omit to start a new conversation.
	ConversationID string `json:"conversationId,omitempty"`
	// Streaming should generally be false for synchronous responses.
	Streaming bool             `json:"streaming"`
	Contact   *ChatvoltContact `json:"contact,omitempty"`
}

ChatvoltAgentQueryRequest is the body for querying a Chatvolt agent.

type ChatvoltAgentQueryResponse

type ChatvoltAgentQueryResponse struct {
	Answer         string      `json:"answer"`
	ConversationID string      `json:"conversationId"`
	MessageID      string      `json:"messageId"`
	VisitorID      string      `json:"visitorId"`
	Sources        interface{} `json:"sources"`
	Metadata       interface{} `json:"metadata"`
}

ChatvoltAgentQueryResponse is the response from a Chatvolt agent query.

type ChatvoltAgentVisibility added in v0.0.4

type ChatvoltAgentVisibility string

ChatvoltAgentVisibility indicates whether a Chatvolt agent is publicly accessible.

const (
	ChatvoltAgentVisibilityPublic  ChatvoltAgentVisibility = "public"
	ChatvoltAgentVisibilityPrivate ChatvoltAgentVisibility = "private"
)

type ChatvoltCase

type ChatvoltCase interface {
	// Configure creates or updates the Chatvolt integration credentials
	// for the authenticated tenant.
	Configure(ctx context.Context, req ConfigureChatvoltRequest) error

	// Query sends a message to a Chatvolt agent and returns its response.
	// Set req.ConversationID to continue an existing conversation thread.
	Query(ctx context.Context, req ChatvoltAgentQueryRequest) (*ChatvoltAgentQueryResponse, error)

	// ListAgents returns all Chatvolt agents available for the authenticated tenant.
	ListAgents(ctx context.Context) (*ListChatvoltAgentsResponse, error)
}

ChatvoltCase provides operations for the Chatvolt agent integration.

type ChatvoltContact

type ChatvoltContact struct {
	UserID      string `json:"userId,omitempty"`
	Email       string `json:"email,omitempty"`
	FirstName   string `json:"firstName,omitempty"`
	LastName    string `json:"lastName,omitempty"`
	PhoneNumber string `json:"phoneNumber,omitempty"`
}

ChatvoltContact carries optional contact metadata attached to a Chatvolt query.

type ChatvoltCredentialsDTO

type ChatvoltCredentialsDTO struct {
	Token string `json:"token"`
}

ChatvoltCredentialsDTO holds the API key for the Chatvolt integration.

type Client

type Client struct {
	// Auth covers login, logout, OTP, password reset, and API token management.
	Auth AuthCase

	// User covers user CRUD operations.
	User UserCase

	// Tenant covers tenant CRUD operations.
	Tenant TenantCase

	// Provider covers read operations for catalog integration providers.
	Provider ProviderCase

	// Service covers read operations for catalog integration services.
	Service ServiceCase

	// Google covers the Google Vision AI integration (configure + OCR).
	Google GoogleCase

	// OpenAI covers the OpenAI integration (configure, chat, image analysis, transcription).
	OpenAI OpenAICase

	// Chatvolt covers the Chatvolt agent integration (configure, query, list agents).
	Chatvolt ChatvoltCase
}

Client is the top-level Synapse SDK entry point. Each field exposes a domain-specific interface covering a group of API endpoints.

Usage:

client, err := synapse.NewClient("your-token", nil)

// Auth
resp, err := client.Auth.Login(ctx, synapse.LoginRequest{...})

// Tenant
tenant, err := client.Tenant.Get(ctx, "uuid", "")

// Google Vision
err = client.Google.Configure(ctx, synapse.ConfigureGoogleRequest{...})
ocr, err := client.Google.VisionOCR(ctx, "photo.jpg", imageBytes)

// OpenAI
reply, err := client.OpenAI.Chat(ctx, synapse.ChatCompletionRequest{Prompt: "Hello!"})

// Chatvolt
answer, err := client.Chatvolt.Query(ctx, synapse.ChatvoltAgentQueryRequest{...})

func NewClient

func NewClient(token string, opts *Options) (*Client, error)

NewClient creates and returns a fully initialised Synapse Client.

token is required and is sent as a Bearer token on every request. Pass an *Options to override the base URL or request timeout; pass nil for defaults.

client, err := synapse.NewClient("sk-...", &synapse.Options{
    BaseURL: "https://staging.synapse.example.com",
    Timeout: 15 * time.Second,
})

type ConfigureChatvoltRequest

type ConfigureChatvoltRequest struct {
	Credentials ChatvoltCredentialsDTO `json:"credentials"`
	IsActive    bool                   `json:"is_active,omitempty"`
}

ConfigureChatvoltRequest is the body for creating/updating the Chatvolt integration.

type ConfigureGoogleRequest

type ConfigureGoogleRequest struct {
	Credentials VisionAICredentialsDTO `json:"credentials"`
	IsActive    bool                   `json:"is_active,omitempty"`
}

ConfigureGoogleRequest is the body for creating/updating the Google Vision integration.

type ConfigureOpenAIRequest

type ConfigureOpenAIRequest struct {
	Credentials OpenAICredentialsDTO `json:"credentials"`
	Settings    OpenAISettingsDTO    `json:"settings"`
	IsActive    bool                 `json:"is_active,omitempty"`
}

ConfigureOpenAIRequest is the body for creating/updating the OpenAI integration.

type CreateTenantRequestDto

type CreateTenantRequestDto struct {
	ID       string `json:"uuid"`
	Name     string `json:"name"`
	Document string `json:"document"`
}

CreateTenantRequestDto is the body for creating a tenant.

type CreateUserRequestDto

type CreateUserRequestDto struct {
	Name     string   `json:"name"`
	Email    string   `json:"email"`
	Password string   `json:"password"`
	Role     UserRole `json:"role"`
}

CreateUserRequestDto is the body for creating a user.

type GoogleCase

type GoogleCase interface {
	// Configure creates or updates the Google Vision AI integration credentials
	// for the authenticated tenant.
	Configure(ctx context.Context, req ConfigureGoogleRequest) error

	// VisionOCR extracts text from an image using Google Vision TEXT_DETECTION.
	// fileName is used as the multipart filename (e.g. "photo.jpg").
	// fileContent is the raw image bytes (png, jpg, jpeg, webp).
	VisionOCR(ctx context.Context, fileName string, fileContent []byte) (*AnalyzeImageResponse, error)
}

GoogleCase provides operations for the Google Vision AI integration.

type ListApiTokensResponse

type ListApiTokensResponse struct {
	UserUUID  string                   `json:"user_uuid"`
	Page      int                      `json:"page"`
	Size      int                      `json:"size"`
	APITokens []ApiTokenCreateResponse `json:"api_tokens"`
}

ListApiTokensResponse is the paginated response for the API token list.

type ListChatvoltAgentsResponse added in v0.0.4

type ListChatvoltAgentsResponse struct {
	Agents []ChatvoltAgentItem `json:"agents"`
}

ListChatvoltAgentsResponse is the response for the Chatvolt agents list endpoint.

type ListUsersParams

type ListUsersParams struct {
	Page int
	Size int
	// TenantIdentifier filters by tenant UUID or document (SystemAdmin only).
	TenantIdentifier string
}

ListUsersParams holds query parameters for the user list endpoint.

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

LoginRequest holds the credentials for the login endpoint.

type LoginResponse

type LoginResponse struct {
	Token         string          `json:"token"`
	Expire        string          `json:"expire"`
	SystemTimeUTC string          `json:"system_time_utc"`
	User          UserResponseDto `json:"user"`
}

LoginResponse is returned on successful login or healthcheck.

type OTPRequest

type OTPRequest struct {
	Email string `json:"email"`
}

OTPRequest requests a one-time password to be sent to the given email.

type OTPResetPasswordRequest

type OTPResetPasswordRequest struct {
	Email    string `json:"email"`
	OTP      string `json:"otp"`
	Password string `json:"password"`
}

OTPResetPasswordRequest resets a user password using an OTP code.

type OpenAICase

type OpenAICase interface {
	// Configure creates or updates the OpenAI integration credentials and settings
	// for the authenticated tenant.
	Configure(ctx context.Context, req ConfigureOpenAIRequest) error

	// Chat executes a Chat Completion call using the tenant's configured OpenAI account.
	Chat(ctx context.Context, req ChatCompletionRequest) (*ChatCompletionResponse, error)

	// AnalyzeImage analyses an image using OpenAI vision.
	// fileName is the multipart filename (e.g. "image.png").
	// fileContent is the raw image bytes (png, jpg, jpeg, webp).
	// prompt describes what analysis to perform.
	AnalyzeImage(ctx context.Context, fileName string, fileContent []byte, prompt string) (*AnalyzeImageResponse, error)

	// TranscribeAudio converts an audio file to text using OpenAI Whisper or GPT-4o.
	// See TranscribeAudioRequest for the full set of options.
	TranscribeAudio(ctx context.Context, req TranscribeAudioRequest) (*TranscriptionResponse, error)
}

OpenAICase provides operations for the OpenAI integration.

type OpenAICredentialsDTO

type OpenAICredentialsDTO struct {
	Token string `json:"token"`
}

OpenAICredentialsDTO holds the API key for the OpenAI integration.

type OpenAIModel

type OpenAIModel string

OpenAIModel is the model identifier accepted by the OpenAI integration.

const (
	OpenAIModelGPT4oMini  OpenAIModel = "gpt-4o-mini"
	OpenAIModelGPT4o      OpenAIModel = "gpt-4o"
	OpenAIModelGPT4_1     OpenAIModel = "gpt-4.1"
	OpenAIModelGPT4_1Mini OpenAIModel = "gpt-4.1-mini"
	OpenAIModelO4Mini     OpenAIModel = "o4-mini"
)

type OpenAISettingsDTO

type OpenAISettingsDTO struct {
	Model OpenAIModel `json:"model"`
	// Temperature ranges 0–2; omitted when zero.
	Temperature float64 `json:"temperature,omitempty"`
}

OpenAISettingsDTO configures model and sampling behaviour.

type Options

type Options struct {
	// BaseURL overrides the default API base URL (https://synapse.wonit.net.br).
	// Useful for staging environments or self-hosted deployments.
	BaseURL string

	// Timeout sets the maximum duration for each HTTP request.
	// Defaults to 30 seconds when zero.
	Timeout time.Duration
}

Options configures the Synapse client at creation time. All fields are optional; zero values fall back to library defaults.

type ProviderCase

type ProviderCase interface {
	// Get fetches a single provider by its UUID.
	Get(ctx context.Context, id string) (*ProviderResponseDto, error)

	// List returns a paginated list of all available providers.
	List(ctx context.Context, page, pageSize int) (*ProvidersResponseDto, error)
}

ProviderCase provides read operations for catalog integration providers.

type ProviderResponseDto

type ProviderResponseDto struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	LogoURL   string `json:"logo_url"`
	Website   string `json:"website"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

ProviderResponseDto describes a catalog integration provider (e.g. Google, OpenAI).

type ProvidersResponseDto

type ProvidersResponseDto struct {
	Page      int                   `json:"page"`
	Size      int                   `json:"size"`
	Providers []ProviderResponseDto `json:"providers"`
}

ProvidersResponseDto is the paginated response for the provider list.

type RestErrCause

type RestErrCause struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

RestErrCause holds a field-level validation detail returned by the API.

type ServiceCase

type ServiceCase interface {
	// Get fetches a single integration service by its UUID.
	Get(ctx context.Context, id string) (*ServiceResponseDto, error)

	// List returns a paginated list of all available integration services.
	List(ctx context.Context, page, pageSize int) (*ServicesResponseDto, error)
}

ServiceCase provides read operations for catalog integration services.

type ServiceResponseDto

type ServiceResponseDto struct {
	ID               string `json:"id"`
	Name             string `json:"name"`
	Slug             string `json:"slug"`
	ProviderID       string `json:"provider_id"`
	BaseURL          string `json:"base_url"`
	AuthType         string `json:"auth_type"`
	DocumentationURL string `json:"documentation_url"`
}

ServiceResponseDto describes a catalog integration service.

type ServicesResponseDto

type ServicesResponseDto struct {
	Page     int                  `json:"page"`
	Size     int                  `json:"size"`
	Services []ServiceResponseDto `json:"services"`
}

ServicesResponseDto is the paginated response for the service list.

type TenantCase

type TenantCase interface {
	// Get fetches a tenant by UUID or document (CNPJ/CPF).
	// At least one of uuid or document must be non-empty.
	Get(ctx context.Context, uuid, document string) (*TenantResponseDto, error)

	// List returns a paginated list of all tenants.
	List(ctx context.Context, page, pageSize int) (*TenantsResponseDto, error)

	// Create registers a new tenant.
	Create(ctx context.Context, req CreateTenantRequestDto) (*TenantResponseDto, error)

	// Update partially updates the tenant identified by uuid.
	Update(ctx context.Context, uuid string, req UpdateTenantRequestDto) (*TenantResponseDto, error)

	// Delete permanently removes a tenant by UUID or document.
	// At least one of uuid or document must be non-empty.
	Delete(ctx context.Context, uuid, document string) error
}

TenantCase provides CRUD operations for tenants within the Synapse API.

type TenantResponseDto

type TenantResponseDto struct {
	UUID      string `json:"uuid"`
	Name      string `json:"name"`
	Document  string `json:"document"`
	Live      bool   `json:"live"`
	CreatedAt string `json:"createAt"`
	UpdatedAt string `json:"updateAt"`
}

TenantResponseDto is the tenant shape returned by the API.

type TenantsResponseDto

type TenantsResponseDto struct {
	Page    int                 `json:"page"`
	Size    int                 `json:"size"`
	Tenants []TenantResponseDto `json:"tenants"`
}

TenantsResponseDto is the paginated response for the tenant list.

type TranscribeAudioRequest

type TranscribeAudioRequest struct {
	// FileName is used as the multipart filename (e.g. "recording.mp3").
	FileName string
	// Content is the raw audio file bytes.
	Content []byte
	// Model selects the transcription engine: whisper-1 | gpt-4o-transcribe | gpt-4o-mini-transcribe.
	Model string
	// Language hints the spoken language (e.g. "pt", "en", "es").
	Language string
	// Prompt is optional auxiliary text to improve transcription accuracy.
	Prompt string
}

TranscribeAudioRequest groups all parameters for the audio transcription endpoint.

type TranscriptionResponse

type TranscriptionResponse struct {
	Response string `json:"response"`
}

TranscriptionResponse is the response from the audio transcription endpoint.

type UpdateTenantRequestDto

type UpdateTenantRequestDto struct {
	Name     string `json:"name,omitempty"`
	Document string `json:"document,omitempty"`
	// Live uses a pointer so false can be distinguished from omitted.
	Live *bool `json:"live,omitempty"`
}

UpdateTenantRequestDto is the body for partially updating a tenant.

type UpdateUserRequestDto

type UpdateUserRequestDto struct {
	Name     string   `json:"name,omitempty"`
	Email    string   `json:"email,omitempty"`
	Password string   `json:"password,omitempty"`
	Role     UserRole `json:"role,omitempty"`
}

UpdateUserRequestDto is the body for partially updating a user.

type UserCase

type UserCase interface {
	// Get returns a single user by UUID or email.
	// Pass the authenticated user's own identifier to fetch their profile.
	Get(ctx context.Context, identifier string) (*UserResponseDto, error)

	// List returns a paginated list of users.
	// SystemAdmin can filter by tenant using params.TenantIdentifier.
	List(ctx context.Context, params ListUsersParams) ([]UserResponseDto, error)

	// Create registers a new user under the given tenant identifier (UUID or document).
	Create(ctx context.Context, tenantIdentifier string, req CreateUserRequestDto) (*UserResponseDto, error)

	// Update partially updates a user identified by UUID or email.
	Update(ctx context.Context, identifier string, req UpdateUserRequestDto) (*UserResponseDto, error)

	// Delete permanently removes a user identified by UUID or email.
	Delete(ctx context.Context, identifier string) error
}

UserCase provides CRUD operations for users within the Synapse API.

type UserResponseDto

type UserResponseDto struct {
	UUID       string   `json:"uuid"`
	Name       string   `json:"name"`
	Email      string   `json:"email"`
	Role       UserRole `json:"role"`
	TenantUUID string   `json:"tenant_uuid"`
	Live       bool     `json:"live"`
	CreatedAt  string   `json:"create_at"`
	UpdatedAt  string   `json:"update_at"`
}

UserResponseDto is the user shape returned by the API.

type UserRole

type UserRole string

UserRole represents the access level of a user within the system.

const (
	UserRoleSystemAdmin UserRole = "SYSTEM_ADMIN"
	UserRoleTenantAdmin UserRole = "TENANT_ADMIN"
	UserRoleTenantUser  UserRole = "TENANT_USER"
)

type VisionAICredentialsDTO

type VisionAICredentialsDTO struct {
	Token string `json:"token"`
}

VisionAICredentialsDTO holds the API key for the Google Vision integration.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL