Share Link Authentication

FastGPT Share Link Authentication

Introduction

In FastGPT V4.6.4, we changed how share links read data. A localId is generated for each user to identify them and pull chat history from the cloud. However, this only works on the same device and browser -- switching devices or clearing browser cache will lose those records. Due to this limitation, we only allow users to pull the last 20 records from the past 30 days.

Share link authentication is designed to quickly and securely integrate FastGPT's chat interface into your existing system with just 2 endpoints. This feature is only available in the commercial edition.

Usage Guide

In the share link configuration, you can optionally fill in the Identity Verification field. This is the root URL for a POST request. Once configured, share link initialization, chat start, and chat completion will all send requests to specific endpoints under this URL. Below, we use host to represent the identity verification root URL. Your server only needs to return whether verification succeeded -- no other data is required. The format is as follows:

Unified Response Format

{
  "success": true,
  "message": "Error message",
  "msg": "Same as message, error message",
  "data": {
    "uid": "Unique user identifier" // Required
  }
}

FastGPT checks whether success is true to decide if the user can proceed. message and msg are equivalent -- you can return either one. When success is not true, this error message will be displayed to the user.

uid is the unique user identifier and must be returned. The ID format must be a string that does not contain |, /, or \\ characters, with a length of 255 bytes or less. Otherwise, an Invalid UID error will be returned. The uid is used to pull and save chat history -- see the practical example below.

Flow Diagram

Configuration Guide

1. Configure the Identity Verification URL

Once configured, every time the share link is used, verification and reporting requests will be sent to the corresponding endpoints.

You only need to configure the root URL here -- no need to specify the full request path.

Add an extra parameter authToken to the share link URL. For example:

Original link: https://share.fastgpt.io/chat/share?shareId=648aaf5ae121349a16d62192

Full link: https://share.fastgpt.io/chat/share?shareId=648aaf5ae121349a16d62192&authToken=userid12345

This authToken is typically a unique user credential (such as a token) generated by your system. FastGPT will include token=[authToken] in the body of the verification request.

3. Implement the Chat Initialization Verification Endpoint

curl --location --request POST '{{host}}/shareAuth/init' \
--header 'Content-Type: application/json' \
--data-raw '{
    "token": "[authToken]"
}'
{
  "success": true,
  "data": {
    "uid": "Unique user identifier"
  }
}

The system will pull chat history for uid username123 under this share link.

{
  "success": false,
  "message": "Authentication failed"
}

4. Implement the Pre-Chat Verification Endpoint

curl --location --request POST '{{host}}/shareAuth/start' \
--header 'Content-Type: application/json' \
--data-raw '{
    "token": "[authToken]",
    "question": "User question",
}'
{
  "success": true,
  "data": {
    "uid": "Unique user identifier"
  }
}
{
  "success": false,
  "message": "Authentication failed"
}
{
  "success": false,
  "message": "Content policy violation"
}

5. Implement the Chat Result Reporting Endpoint (Optional)

This endpoint has no required response format.

The response data follows the same format as the chat endpoint, with an additional token field.

Key fields to note: totalPoints (total AI credits consumed), token (total token consumption)

curl --location --request POST '{{host}}/shareAuth/finish' \
--header 'Content-Type: application/json' \
--data-raw '{
    "token": "[authToken]",
    "responseData": [
        {
            "moduleName": "core.module.template.Dataset search",
            "moduleType": "datasetSearchNode",
            "totalPoints": 1.5278,
            "query": "导演是谁\n《铃芽之旅》的导演是谁?\n这部电影的导演是谁?\n谁是《铃芽之旅》的导演?",
            "model": "Embedding-2(旧版,不推荐使用)",
            "tokens": 1524,
            "similarity": 0.83,
            "limit": 400,
            "searchMode": "embedding",
            "searchUsingReRank": false,
            "extensionModel": "FastAI-4k",
            "extensionResult": "《铃芽之旅》的导演是谁?\n这部电影的导演是谁?\n谁是《铃芽之旅》的导演?",
            "runningTime": 2.15
        },
        {
            "moduleName": "AI 对话",
            "moduleType": "chatNode",
            "totalPoints": 0.593,
            "model": "FastAI-4k",
            "tokens": 593,
            "query": "导演是谁",
            "maxToken": 2000,
            "quoteList": [
                {
                    "id": "65bb346a53698398479a8854",
                    "q": "导演是谁?",
                    "a": "电影《铃芽之旅》的导演是新海诚。",
                    "chunkIndex": 0,
                    "datasetId": "65af9b947916ae0e47c834d2",
                    "collectionId": "65bb345c53698398479a868f",
                    "sourceName": "dataset - 2024-01-23T151114.198.csv",
                    "sourceId": "65bb345b53698398479a868d",
                    "score": [
                        {
                            "type": "embedding",
                            "value": 0.9377183318138123,
                            "index": 0
                        },
                        {
                            "type": "rrf",
                            "value": 0.06557377049180328,
                            "index": 0
                        }
                    ]
                }
            ],
            "historyPreview": [
                {
                    "obj": "Human",
                    "value": "使用 <Data></Data> 标记中的内容作为本次对话的参考:\n\n<Data>\n导演是谁?\n电影《铃芽之旅》的导演是新海诚。\n------\n电影《铃芽之旅》的编剧是谁?22\n新海诚是本片的编剧。\n------\n电影《铃芽之旅》的女主角是谁?\n电影的女主角是铃芽。\n------\n电影《铃芽之旅》的制作团队中有哪位著名人士?2\n川村元气是本片的制作团队成员之一。\n------\n你是谁?\n我是电影《铃芽之旅》助手\n------\n电影《铃芽之旅》男主角是谁?\n电影《铃芽之旅》男主角是宗像草太,由松村北斗配音。\n------\n电影《铃芽之旅》的作者新海诚写了一本小说,叫什么名字?\n小说名字叫《铃芽之旅》。\n------\n电影《铃芽之旅》的女主角是谁?\n电影《铃芽之旅》的女主角是岩户铃芽,由原菜乃华配音。\n------\n电影《铃芽之旅》的故事背景是什么?\n日本\n------\n谁担任电影《铃芽之旅》中岩户环的配音?\n深津绘里担任电影《铃芽之旅》中岩户环的配音。\n</Data>\n\n回答要求:\n- 如果你不清楚答案,你需要澄清。\n- 避免提及你是从 <Data></Data> 获取的知识。\n- 保持答案与 <Data></Data> 中描述的一致。\n- 使用 Markdown 语法优化回答格式。\n- 使用与问题相同的语言回答。\n\n问题:\"\"\"导演是谁\"\"\""
                },
                {
                    "obj": "AI",
                    "value": "电影《铃芽之旅》的导演是新海诚。"
                }
            ],
            "contextTotalLen": 2,
            "runningTime": 1.32
        }
    ]


}'

Full responseData Field Reference:

type ResponseType = {
  moduleType: FlowNodeTypeEnum; // Module type
  moduleName: string; // Module name
  moduleLogo?: string; // Logo
  runningTime?: number; // Running time
  query?: string; // User question / search query
  textOutput?: string; // Text output

  tokens?: number; // Total context tokens
  model?: string; // Model used
  contextTotalLen?: number; // Total context length
  totalPoints?: number; // Total AI credits consumed

  temperature?: number; // Temperature
  maxToken?: number; // Model max tokens
  quoteList?: SearchDataResponseItemType[]; // Citation list
  historyPreview?: ChatItemType[]; // Context preview (history may be truncated)

  similarity?: number; // Minimum similarity threshold
  limit?: number; // Max citation tokens
  searchMode?: `${DatasetSearchModeEnum}`; // Search mode
  searchUsingReRank?: boolean; // Whether rerank is used
  extensionModel?: string; // Query expansion model
  extensionResult?: string; // Query expansion result
  extensionTokens?: number; // Query expansion total token length

  cqList?: ClassifyQuestionAgentItemType[]; // Question classification list
  cqResult?: string; // Question classification result

  extractDescription?: string; // Content extraction description
  extractResult?: Record<string, any>; // Content extraction result

  params?: Record<string, any>; // HTTP module params
  body?: Record<string, any>; // HTTP module body
  headers?: Record<string, any>; // HTTP module headers
  httpResult?: Record<string, any>; // HTTP module result

  pluginOutput?: Record<string, any>; // Plugin output
  pluginDetail?: ChatHistoryItemResType[]; // Plugin details

  isElseResult?: boolean; // Conditional result
};

Practical Example

We'll use Laf as the server to demonstrate how these 3 endpoints work.

1. Create 3 Laf Endpoints

In this endpoint, we require token to equal fastgpt to pass verification. (Not recommended for production -- avoid hardcoding values.)

import cloud from '@lafjs/cloud';

export default async function (ctx: FunctionContext) {
  const { token } = ctx.body;

  // Token decoding logic omitted
  if (token === 'fastgpt') {
    return { success: true, data: { uid: 'user1' } };
  }

  return { success: false, message: 'Authentication failed' };
}

In this endpoint, we require token to equal fastgpt to pass verification. Additionally, if the question contains a specific character, it returns an error to simulate content moderation.

import cloud from '@lafjs/cloud';

export default async function (ctx: FunctionContext) {
  const { token, question } = ctx.body;

  // Token decoding logic omitted
  if (token !== 'fastgpt') {
    return { success: false, message: 'Authentication failed' };
  }

  if (question.includes('你')) {
    return { success: false, message: 'Content policy violation' };
  }

  return { success: true, data: { uid: 'user1' } };
}

The result reporting endpoint can handle custom logic as needed.

import cloud from '@lafjs/cloud';

export default async function (ctx: FunctionContext) {
  const { token, responseData } = ctx.body;

  const total = responseData.reduce((sum, item) => sum + item.price, 0);
  const amount = total / 100000;

  // Database operations omitted

  return {};
}

2. Configure the Verification URL

Copy any of the 3 endpoint URLs, e.g. https://d8dns0.laf.dev/shareAuth/finish, remove the /shareAuth/finish part, and enter the root URL https://d8dns0.laf.dev in the Identity Verification field.

Original share link: https://share.fastgpt.io/chat/share?shareId=64be36376a438af0311e599c

Modified: https://share.fastgpt.io/chat/share?shareId=64be36376a438af0311e599c&authToken=fastgpt

4. Test the Result

  1. Opening the original link or a link where authToken does not equal fastgpt will show an authentication error.
  2. Sending content that contains the filtered character will show a content policy violation error.

Use Cases

This authentication method is typically used to embed the share link directly into your application. Before opening the share link in your app, you should append the authToken parameter.

Beyond integrating with your existing user system, you can also implement a balance feature -- deduct user balance via the result reporting endpoint and check user balance via the pre-chat verification endpoint.

Edit on GitHub

File Updated