@florentine-ai/api

中文文档
1.0.0发布于 2026/03/09MITTypeScriptES Module近 30 天下载 1万

Node.js API Wrapper for Florentine.ai – query MongoDB & MySQL databases in natural language

原始使用文档
文档目录19 节
  1. Contents
  2. Prerequisites
  3. Installation
  4. Authentication
  5. Connect your LLM account
  6. Option 1: Save your LLM key in your account (recommended)
  7. Option 2: Provide your LLM key in API requests
  8. First Request
  9. Return Types
  10. Example returning all three steps
  11. Secure Data Separation for multi-tenant usage
  12. Providing Required Inputs
  13. Required Inputs Configuration
  14. Supported Value Types
  15. Usage Examples
  16. Sessions
  17. Errors
  18. Handle errors in client
  19. Common Errors

Florentine.ai API - Talk to your MongoDB & MySQL data

The Florentine.ai API lets you integrate natural language querying for your MongoDB & MySQL data directly into your project.

Questions are transformed into database queries that can also directly be executed and answered in natural language.

Also has a couple of extra features under the hood, e.g.:

  • Secure data separation for multi-tenant usage
  • Automated schema exploration
  • Semantic vector search/RAG support with automated embedding creation
  • Advanced lookup support
  • Exclusion of keys

[!NOTE] If you are looking for our MCP Server you can find it here.

Contents

Prerequisites

  • Node.js >= v18.0.0
  • A Florentine.ai account (create a free account here)
  • A connected database and at least one analyzed and activated collection/table in your Florentine.ai account
  • A Florentine.ai API Key (you can find yours on your account dashboard)

Installation

A detailed documentation of the API can be found here in our docs.

npm install @florentine-ai/api

Authentication

import { Florentine } from '@florentine-ai/api';

const FlorentineAI = new Florentine({
  florentineToken: '<FLORENTINE_API_KEY>'
});

Connect your LLM account

Florentine.ai works as a bring your own key model, so you need to provide your LLM API key (OpenAI, Google, Anthropic, Deepseek) in your API requests.

You have two options how you can add your LLM API key:

The easiest way to connect to your LLM provider is to save your LLM API key in your Florentine.ai dashboard.

  • Add your API key
  • Select your LLM provider (OpenAI, Deepseek, Google or Anthropic)
  • Click Save

Add your LLM key

Option 2: Provide your LLM key in API requests

If you prefer not to store the key in your Florentine.ai account or want to use multiple LLM keys, you can pass the key in your API request.

Add the values as llmService and llmKey to the class constructor object:

const FlorentineAI = new Florentine({
  florentineToken: '<FLORENTINE_API_KEY>',
  llmService: '<YOUR_LLM_SERVICE>', // one of: "openai", "google", "anthropic", "deepseek"
  llmKey: '<YOUR_LLM_API_KEY>'
});

[!NOTE] If you provide an llmKey inside the request, it will override any key stored in your account.

First Request

You should now be ready to send your first API request!

Come up with a question that can be answered via the data in your activated collection(s)/table(s) and pass it to the .ask() method:

const FlorentineAI = new Florentine({
  florentineToken: '<FLORENTINE_API_KEY>'
});

const res = await FlorentineAI.ask({
  question: '<YOUR_QUESTION>',
  sessionId: 'FIRST_REQUEST'
});

By default, the API returns the raw query result. The return type can be configured via returnTypes.

Imagine a tabletennis collection that records the results of the matches of two players. If I ask the question Who won the last match? the answer might look similar to this:

{
  "answer": "Frank won the last match. According to our records, he emerged as the winner, highlighting his strong performance in that game."
}

Return Types

In the background, three steps happen for every request:

  1. Query Generation: The question is converted into a database query (MongoDB aggregation pipeline or MySQL query).
  2. Query Execution: The query runs against the database using the connection string you provided.
  3. Answer Generation: The structured result is transformed into a natural language answer.

The default return type is configured in your Florentine.ai account. You can override it per request by specifying a returnTypes array with any combination of:

returnTypes ValueDescriptionExpected Keys in Response
"query"Returns the generated database query, the database and collection/table used, a confidence score on a scale from 0 to 10 and the database type ("mongodb" or "mysql").confidence, database, collection, query, databaseType
"result"Returns the raw query results from the executed query.result
"answer"Returns a natural language response based on the results from the executed query.answer

Example returning all three steps

Let's imagine the tabletennis example from the first request section once more.
With all three steps the request looks like this:

const res = await FlorentineAI.ask({
  question: 'Who won the last match?',
  returnTypes: ['query', 'result', 'answer']
});

And the response looks like this:

{
  "database": "samples",
  "collection": "tabletennis",
  "databaseType": "mongodb",
  "query": [
    { "$sort": { "year": -1, "matchInYear": -1 } },
    { "$limit": 1 },
    {
      "$project": {
        "winner": {
          "$cond": {
            "if": { "$eq": ["$matchwinner", "home"] },
            "then": "$players.home",
            "else": "$players.away"
          }
        }
      }
    }
  ],
  "result": [{ "_id": "67d352056d3ef0f2281524cf", "winner": "Frank" }],
  "answer": "Frank won the last match. According to our records, he emerged as the winner, highlighting his strong performance in that game."
}

Secure Data Separation for multi-tenant usage

You can enable secure data separation by ensuring queries filter data based on provided values which we call Required Inputs.

These values are added to the query by the Florentine.ai transformation layer after the query generation by the LLM. Thus Florentine.ai can assure each user only retrieves the data he is eligible to.

Keys are defined as Required Input in your account, please refer to the section in our official docs on how to do that.

Providing Required Inputs

Provide your Required Inputs inside a requiredInputs array with keyPath and value for each key you set as Required Input and add it to the .ask() method:

const res = await FlorentineAI.ask({
  question: 'What is the revenue of my products this year?',
  requiredInputs: [
    {
      keyPath: 'accountId',
      value: '507f1f77bcf86cd799439011'
    }
  ]
});

You may also provide a database and a collections array in case you have Required Inputs with the same keyPath in multiple collections/tables but different value for the collections/tables:

const res = await FlorentineAI.ask({
  question: 'Whats the current monthly rent of my tenants?',
  requiredInputs: [
    {
      keyPath: 'name',
      value: 'Sesame Street',
      database: 'rentals',
      collections: ['houses']
    },
    {
      keyPath: 'name',
      value: { $in: ['Ernie', 'Bert'] },
      database: 'rentals',
      collections: ['tenants']
    }
  ]
});

Required Inputs Configuration

FieldRequiredTypeDescriptionConstraints
keyPathYesStringThe path to the field that should be filtered.Must be a valid key path.
valueYesAnyThe value(s) to filter by (type-specific, see Supported Value Types).Must match the field's type (String, ObjectId, Boolean, Number, or Date).
databaseNoStringThe database containing the collections to filter.Must be provided if collections is provided.
collectionsNoArray<String>The specific collections/tables within the database to apply the filter to.Must contain at least one collection/table.

Supported Value Types

Based on the type of the values for the key you have different options on what you can provide as a Required Input value:

TypeFormat ExamplesOperators SupportedNotes
String or Array<String>"text"
{ $in: ["text1", "text2"] }
$inCase-sensitive.
ObjectId or Array<ObjectId>"507f191e810c19729de860ea"
{ $in: ["507f191e810c19729de860ea", "507f191e810c19729de860eb"] }
$inProvided as strings.
Booleantrue/false—Only exact values.
Number or Array<Number>42
{ $gt: 10, $lte: 100 }
{ $in: [1, 2, 3] }
{ $in: [{$gte:1}, {$lt:10}] }
$gt, $gte, $lt, $lte, $inSupports decimals.
Date or Array<Date>"2024-01-01T00:00:00Z" (UTC)
"2024-01-01T00:00:00-05:00"(timezone offset)
$gt, $gte, $lt, $lte, $inISO 8601 format.

Usage Examples

Example type: String

Usecase: A user should only be able to see statistics of the players he frequently plays with.

Solution: Restricting access by player name to a group of 4 players.

const res = await FlorentineAI.ask({
  question: 'Which player had the most wins?',
  requiredInputs: [
    {
      keyPath: 'name',
      value: { $in: ['Megan', 'Frank', 'Jen', 'Bob'] }
    }
  ]
});

Example type: ObjectId

Usecase: A user should only be able to see the revenue of his own products.

Solution: Restricting the access by the accountId to one specific account.

const res = await FlorentineAI.ask({
  question: 'Whats the revenue of my products?',
  requiredInputs: [
    {
      keyPath: 'accountId',
      value: '507f1f77bcf86cd799439011'
    }
  ]
});

Example type: Boolean

Usecase: Every analysis of customers should only be performed on paying customers.

Solution: Restricting the access by isPaidAccount to paying customers only.

const res = await FlorentineAI.ask({
  question: 'How many customers registered in the last year?',
  requiredInputs: [
    {
      keyPath: 'isPaidAccount',
      value: true
    }
  ]
});

Example type: Number

Usecase: An employee should only be allowed to see payment information for payments below a certain amount.

Solution: Restricting the access by amount to payments below 10.000.

const res = await FlorentineAI.ask({
  question: 'List all payments we received.',
  requiredInputs: [
    {
      keyPath: 'amount',
      value: { $lt: 10000 }
    }
  ]
});

Example type: Date

Usecase: The analysis of financial data should only include one specific year.

Solution: Restricting the access by transactionDate to all transactions in 2024.

const res = await FlorentineAI.ask({
  question: 'What was our revenue, profit and margin per month?',
  requiredInputs: [
    {
      keyPath: 'transactionDate',
      value: {
        $gte: '2023-01-01T00:00:00Z',
        $lt: '2024-01-01T00:00:00Z'
      }
    }
  ]
});

Sessions

Sessions allow Florentine.ai to enable a server-side chat history. Just provide a sessionId string like this:

const res = await FlorentineAI.ask({
  question: 'What is the revenue of my products this year?',
  sessionId: '<YOUR_SESSION_ID>'
});

Sessions are mandatory unless you disable the server-side chat history by setting withHistory to false inside the constructor:

const FlorentineAI = new Florentine({
  florentineToken: '<FLORENTINE_API_KEY>',
  withHistory: false
});

[!NOTE] It is strongly recommended to use a sessionId to have meaningful multi-turn conversations.

Errors

All errors from the Florentine.ai API follow this consistent JSON structure:

{
  "error": {
    "name": "FlorentineApiError",
    "statusCode": 401,
    "message": "Please provide your Florentine API key. You can find it in your account settings: https://florentine.ai/settings",
    "errorCode": "NO_TOKEN",
    "requestId": "abc123"
  }
}
FieldTypeDescription
namestringError class name (e.g. FlorentineApiError, FlorentineConnectionError)
statusCodenumberHTTP status code (e.g. 400, 500)
messagestringExplanation of what went wrong
errorCodestringError identifier (e.g. NO_TOKEN, INVALID_LLM_KEY)
requestIdstringUnique ID for this request (helpful for support and debugging)

Handle errors in client

API errors are automatically thrown as JavaScript error classes:

import { Florentine, FlorentineApiError } from '@florentine-ai/api';

try {
  const FlorentineAI = new Florentine({});
  const res: TFlorentineReturnOutput = await FlorentineAI.ask({
    question: 'Who is Florentine?'
  });
} catch (err) {
  if (err instanceof FlorentineApiError) {
    console.error(err.message); // "Please provide your Florentine API key."
    console.error(err.statusCode); // 401
    console.error(err.errorCode); // "NO_TOKEN"
    console.error(err.requestId); // "abc123"
  }
}

All client errors extend the FlorentineError class, so you can catch all client related errors like this:

if (err instanceof FlorentineError) {
  // Catches all florentine npm package errors
}

Common Errors

Error TypeerrorCodeMeaning
FlorentineApiErrorNO_TOKENThe Florentine API key is missing
FlorentineApiErrorINVALID_TOKENThe Florentine API key is invalid
FlorentineApiErrorLLM_KEY_WITHOUT_SERVICEYou must provide a llmService if llmKey is defined
FlorentineApiErrorLLM_SERVICE_WITHOUT_KEYYou must provide a llmKey if llmService is defined
FlorentineApiErrorINVALID_LLM_SERVICEInvalid llmService provided
FlorentineApiErrorNO_OWN_LLM_KEYYou need to provide your own llm key
FlorentineApiErrorNO_ACTIVE_COLLECTIONSNo collections/tables activated for the account
FlorentineApiErrorMISSING_REQUIRED_INPUTRequired input is missing
FlorentineApiErrorINVALID_REQUIRED_INPUTRequired input is invalid
FlorentineApiErrorINVALID_REQUIRED_INPUT_FORMATRequired input format is invalid
FlorentineApiErrorNO_QUESTIONQuestion is missing
FlorentineApiErrorEXECUTION_FAILURECreated query execution failed
FlorentineApiErrorNO_CHAT_IDHistory chat id required but missing
FlorentineLLMErrorAPI_KEY_ISSUELLM API key is invalid
FlorentineLLMErrorNO_RETURNFlorentine.ai did not receive a valid LLM return
FlorentineLLMErrorRATE_LIMIT_EXCEEDEDLLM Request size too big
FlorentineApiErrorTOO_MANY_TOKENSThe query prompt exceeds the maximum tokens of the LLM model
FlorentineConnectionErrorCONNECTION_REFUSEDCould not connect to database for query execution
FlorentineCollectionErrorNO_EXECUTIONCreated query could not be executed
FlorentinePipelineErrorMODIFICATION_FAILEDModifying the query pipeline failed
FlorentineUsageErrorLIMIT_REACHEDAll API requests included in your plan depleted
FlorentineUnknownErrorUNKNOWN_ERRORAll occurring unknown errors

版本与发布记录

@florentine-ai/api 共发布 2 个版本,首次发布于 2025/09/09;过去 12 个月发布了 1 个版本。

版本发布日期距今
1.0.0latest2026/03/098 个月前
0.1.02025/09/091.2 年前

关于 @florentine-ai/api 的常见问题

@florentine-ai/api 是什么?

Node.js API Wrapper for Florentine.ai – query MongoDB & MySQL databases in natural language

如何安装 @florentine-ai/api?

在项目目录运行 npm install @florentine-ai/api,或使用 pnpm add / yarn add / bun add。

@florentine-ai/api 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@florentine-ai/api 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@florentine-ai/api 可以商用吗?

@florentine-ai/api 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@florentine-ai/api 的下载量有多少?

根据 npm 官方下载统计,@florentine-ai/api 在 2026/10/15 – 2026/11/13 这 30 天内被下载 10,203 次,日均约 340 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@florentine-ai/api 还在维护吗?

最新版本 1.0.0 发布于 2026/03/09(8 个月前);至今共发布 2 个版本,其中过去 12 个月发布了 1 个;首次发布于 2025/09/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。