API

description: >- Aprende más sobre los detalles de algunas de las APIs más utilizadas: prediction, vector-upsert

API

Consulta la Referencia de API para ver la lista completa de APIs públicas

Prediction

Create a new prediction

post

Create a new prediction

Authorizations
Path parameters
idstringRequired

Chatflow ID

Body
questionstringOptional

The question being asked

overrideConfigobjectOptional

The configuration to override the default prediction settings (optional)

Responses
200
Prediction created successfully
application/json
post
POST /prediction/{id} HTTP/1.1
Host: 
Authorization: Bearer JWT
Content-Type: application/json
Accept: */*
Content-Length: 278

{
  "question": "text",
  "overrideConfig": {},
  "history": [
    {
      "role": "apiMessage",
      "content": "Hello, how can I help you?"
    }
  ],
  "uploads": [
    {
      "type": "file",
      "name": "image.png",
      "data": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAABjElEQVRIS+2Vv0oDQRDG",
      "mime": "image/png"
    }
  ]
}
{
  "text": "text",
  "json": {},
  "question": "text",
  "chatId": "text",
  "chatMessageId": "text",
  "sessionId": "text",
  "memoryType": "text",
  "sourceDocuments": [
    {
      "pageContent": "This is the content of the page.",
      "metadata": {
        "author": "John Doe",
        "date": "2024-08-24"
      }
    }
  ],
  "usedTools": [
    {
      "tool": "Name of the tool",
      "toolInput": {
        "input": "search query"
      },
      "toolOutput": "text"
    }
  ],
  "fileAnnotations": [
    {
      "filePath": "path/to/file",
      "fileName": "file.txt"
    }
  ]
}

Usando Python/TS Library

Flowise proporciona 2 librerías:

from flowise import Flowise, PredictionData

def test_non_streaming():
    client = Flowise()

    # Test de predicción sin streaming
    completion = client.create_prediction(
        PredictionData(
            chatflowId="<chatflow-id>",
            question="¿Cuál es la capital de Francia?",
            streaming=False
        )
    )

    # Procesar e imprimir la respuesta
    for response in completion:
        print("Respuesta sin streaming:", response)

def test_streaming():
    client = Flowise()

    # Test de predicción con streaming
    completion = client.create_prediction(
        PredictionData(
            chatflowId="<chatflow-id>",
            question="¡Cuéntame un chiste!",
            streaming=True
        )
    )

    # Procesar e imprimir cada fragmento del stream
    print("Respuesta con streaming:")
    for chunk in completion:
        print(chunk)


if __name__ == "__main__":
    # Ejecutar test sin streaming
    test_non_streaming()

    # Ejecutar test con streaming
    test_streaming()

Override Config

Sobrescribe la configuración de entrada existente del chatflow con la propiedad overrideConfig.

Por razones de seguridad, la sobrescritura de configuración está deshabilitada por defecto. El usuario debe habilitarla yendo a Chatflow Configuration -> pestaña Security. Luego seleccionar la propiedad que puede ser sobrescrita.

import requests
API_URL = "http://localhost:3000/api/v1/prediction/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    return response.json()
    
output = query({
    "question": "Hola, ¿cómo estás?",
    "overrideConfig": {
        "sessionId": "123",
        "returnSourceDocuments": true
    }
})

History

Puedes anteponer mensajes del historial para dar contexto al LLM. Por ejemplo, si quieres que el LLM recuerde el nombre del usuario:

import requests
API_URL = "http://localhost:3000/api/v1/prediction/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    return response.json()
    
output = query({
    "question": "Hola, ¿cómo estás?",
    "history": [
        {
            "role": "apiMessage",
            "content": "¿Hola, en qué puedo ayudarte?"
        },
        {
            "role": "userMessage",
            "content": "Hola, mi nombre es Brian"
        },
        {
            "role": "apiMessage",
            "content": "Hola Brian, ¿en qué puedo ayudarte?"
        },
    ]
})

Persists Memory

Puedes pasar un sessionId para persistir el estado de la conversación, de modo que cada llamada API posterior tendrá contexto sobre la conversación anterior. De lo contrario, se generará una nueva sesión cada vez.

import requests
API_URL = "http://localhost:3000/api/v1/prediction/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    return response.json()
    
output = query({
    "question": "Hola, ¿cómo estás?",
    "overrideConfig": {
        "sessionId": "123"
    } 
})

Variables

Pasa variables en la API para ser utilizadas por los nodos en el flujo. Ver más: Variables

import requests
API_URL = "http://localhost:3000/api/v1/prediction/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    return response.json()
    
output = query({
    "question": "Hola, ¿cómo estás?",
    "overrideConfig": {
        "vars": {
            "foo": "bar"
        }
    }
})

Image Uploads

Cuando Allow Image Upload está habilitado, las imágenes pueden ser cargadas desde la interfaz de chat.

import requests
API_URL = "http://localhost:3000/api/v1/prediction/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    return response.json()
    
output = query({
    "question": "¿Puedes describir la imagen?",
    "uploads": [
        {
            "data": 'data:image/png;base64,iVBORw0KGgdM2uN0', # base64 string or url
            "type": 'file', # file | url
            "name": 'Flowise.png',
            "mime": 'image/png'
        }
    ]
})

Speech to Text

Cuando Speech to Text está habilitado, los usuarios pueden hablar directamente en el micrófono y la voz se transcribirá en texto.

import requests
API_URL = "http://localhost:3000/api/v1/prediction/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    return response.json()
    
output = query({
    "uploads": [
        {
            "data": 'data:audio/webm;codecs=opus;base64,GkXf', #base64 string
            "type": 'audio',
            "name": 'audio.wav',
            "mime": 'audio/webm'
        }
    ]
})

Vector Upsert API

Upsert vector embeddings

post

Upsert vector embeddings of documents in a chatflow

Authorizations
Path parameters
idstringRequired

Chatflow ID

Body
stopNodeIdstringOptional

In cases when you have multiple vector store nodes, you can specify the node ID to store the vectors

Example: node_1
overrideConfigobjectOptional

The configuration to override the default vector upsert settings (optional)

Responses
200
Vector embeddings upserted successfully
application/json
post
POST /vector/upsert/{id} HTTP/1.1
Host: 
Authorization: Bearer JWT
Content-Type: application/json
Accept: */*
Content-Length: 43

{
  "stopNodeId": "node_1",
  "overrideConfig": {}
}
{
  "numAdded": 1,
  "numDeleted": 1,
  "numUpdated": 1,
  "numSkipped": 1,
  "addedDocs": [
    {
      "pageContent": "This is the content of the page.",
      "metadata": {
        "author": "John Doe",
        "date": "2024-08-24"
      }
    }
  ]
}

Document Loaders with File Upload

Algunos document loaders en Flowise permiten al usuario cargar archivos:

Si el flujo contiene Document Loaders con la funcionalidad de carga de archivo, la API se ve ligeramente diferente. En lugar de pasar el cuerpo como JSON, form data se utiliza. Esto te permite enviar archivos a la API. If the flow contains Document Loaders with Upload File functionality, the API looks slightly different. Instead of passing body as JSON, form data is being used. This allows you to send files to the API.

Make sure the sent file type is compatible with the expected file type from document loader. For example, if a PDF File Loader is being used, you should only send .pdf files.

To avoid having separate loaders for different file types, we recommend to use File Loader

import requests

API_URL = "http://localhost:3000/api/v1/vector/upsert/<chatflowId>"

# use form data to upload files
form_data = {
    "files": ('state_of_the_union.txt', open('state_of_the_union.txt', 'rb'))
}

body_data = {
    "returnSourceDocuments": True
}

def query(form_data):
    response = requests.post(API_URL, files=form_data, data=body_data)
    print(response)
    return response.json()

output = query(form_data)
print(output)

Document Loaders without Upload

For other Document Loaders nodes without Upload File functionality, the API body is in JSON format similar to Prediction API.

import requests

API_URL = "http://localhost:3000/api/v1/vector/upsert/<chatflowId>"

def query(payload):
    response = requests.post(API_URL, json=payload)
    print(response)
    return response.json()

output = query({
    "overrideConfig": { # optional
        "returnSourceDocuments": true
    }
})
print(output)

Document Upsert/Refresh API

Refer to Document Stores section for more information about how to use the API.

Upsert new document to document store

post

Upsert new document to document store

Authorizations
Path parameters
idstring · uuidRequired

Document store ID

Body
docIdstring · uuidOptional

Document ID within the store. If provided, existing configuration from the document will be used for the new document

Responses
200
Successfully execute upsert operation
application/json
post
POST /document-store/upsert/{id} HTTP/1.1
Host: 
Authorization: Bearer JWT
Content-Type: application/json
Accept: */*
Content-Length: 311

{
  "docId": "123e4567-e89b-12d3-a456-426614174000",
  "loader": {
    "name": "plainText",
    "config": {}
  },
  "splitter": {
    "name": "recursiveCharacterTextSplitter",
    "config": {}
  },
  "embedding": {
    "name": "openAIEmbeddings",
    "config": {}
  },
  "vectorStore": {
    "name": "faiss",
    "config": {}
  },
  "recordManager": {
    "name": "postgresRecordManager",
    "config": {}
  }
}
{
  "numAdded": 1,
  "numDeleted": 1,
  "numUpdated": 1,
  "numSkipped": 1,
  "addedDocs": [
    {
      "pageContent": "This is the content of the page.",
      "metadata": {
        "author": "John Doe",
        "date": "2024-08-24"
      }
    }
  ]
}

Re-process and upsert all documents in document store

post

Re-process and upsert all existing documents in document store

Authorizations
Path parameters
idstring · uuidRequired

Document store ID

Body
Responses
200
Successfully execute refresh operation
application/json
post
POST /document-store/refresh/{id} HTTP/1.1
Host: 
Authorization: Bearer JWT
Content-Type: application/json
Accept: */*
Content-Length: 323

{
  "items": [
    {
      "docId": "123e4567-e89b-12d3-a456-426614174000",
      "loader": {
        "name": "plainText",
        "config": {}
      },
      "splitter": {
        "name": "recursiveCharacterTextSplitter",
        "config": {}
      },
      "embedding": {
        "name": "openAIEmbeddings",
        "config": {}
      },
      "vectorStore": {
        "name": "faiss",
        "config": {}
      },
      "recordManager": {
        "name": "postgresRecordManager",
        "config": {}
      }
    }
  ]
}

No content

Video Tutorials

Those video tutorials cover the main use cases for implementing the Flowise API.

Last updated