Merge branch 'langgenius:main' into feat-add-remote-file-upload

pull/18666/head
GuanMu 1 year ago committed by GitHub
commit 2348bea78c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -54,7 +54,7 @@
<a href="./README_BN.md"><img alt="README in বাংলা" src="https://img.shields.io/badge/বাংলা-d9d9d9"></a> <a href="./README_BN.md"><img alt="README in বাংলা" src="https://img.shields.io/badge/বাংলা-d9d9d9"></a>
</p> </p>
Dify is an open-source LLM app development platform. Its intuitive interface combines agentic AI workflow, RAG pipeline, agent capabilities, model management, observability features and more, letting you quickly go from prototype to production. Dify is an open-source LLM app development platform. Its intuitive interface combines agentic AI workflow, RAG pipeline, agent capabilities, model management, observability features, and more, allowing you to quickly move from prototype to production.
## Quick start ## Quick start
@ -188,7 +188,7 @@ All of Dify's offerings come with corresponding APIs, so you could effortlessly
- **Dify for enterprise / organizations</br>** - **Dify for enterprise / organizations</br>**
We provide additional enterprise-centric features. [Log your questions for us through this chatbot](https://udify.app/chat/22L1zSxg6yW1cWQg) or [send us an email](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry) to discuss enterprise needs. </br> We provide additional enterprise-centric features. [Log your questions for us through this chatbot](https://udify.app/chat/22L1zSxg6yW1cWQg) or [send us an email](mailto:business@dify.ai?subject=[GitHub]Business%20License%20Inquiry) to discuss enterprise needs. </br>
> For startups and small businesses using AWS, check out [Dify Premium on AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) and deploy it to your own AWS VPC with one-click. It's an affordable AMI offering with the option to create apps with custom logo and branding. > For startups and small businesses using AWS, check out [Dify Premium on AWS Marketplace](https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6) and deploy it to your own AWS VPC with one click. It's an affordable AMI offering with the option to create apps with custom logo and branding.
## Staying ahead ## Staying ahead
@ -233,7 +233,7 @@ Deploy Dify to AWS with [CDK](https://aws.amazon.com/cdk/)
For those who'd like to contribute code, see our [Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md). For those who'd like to contribute code, see our [Contribution Guide](https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md).
At the same time, please consider supporting Dify by sharing it on social media and at events and conferences. At the same time, please consider supporting Dify by sharing it on social media and at events and conferences.
> We are looking for contributors to help with translating Dify to languages other than Mandarin or English. If you are interested in helping, please see the [i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) for more information, and leave us a comment in the `global-users` channel of our [Discord Community Server](https://discord.gg/8Tpq4AcN9c). > We are looking for contributors to help translate Dify into languages other than Mandarin or English. If you are interested in helping, please see the [i18n README](https://github.com/langgenius/dify/blob/main/web/i18n/README.md) for more information, and leave us a comment in the `global-users` channel of our [Discord Community Server](https://discord.gg/8Tpq4AcN9c).
## Community & contact ## Community & contact

@ -297,6 +297,7 @@ LINDORM_URL=http://ld-*******************-proxy-search-pub.lindorm.aliyuncs.com:
LINDORM_USERNAME=admin LINDORM_USERNAME=admin
LINDORM_PASSWORD=admin LINDORM_PASSWORD=admin
USING_UGC_INDEX=False USING_UGC_INDEX=False
LINDORM_QUERY_TIMEOUT=1
# OceanBase Vector configuration # OceanBase Vector configuration
OCEANBASE_VECTOR_HOST=127.0.0.1 OCEANBASE_VECTOR_HOST=127.0.0.1

@ -271,6 +271,7 @@ def migrate_knowledge_vector_database():
upper_collection_vector_types = { upper_collection_vector_types = {
VectorType.MILVUS, VectorType.MILVUS,
VectorType.PGVECTOR, VectorType.PGVECTOR,
VectorType.VASTBASE,
VectorType.RELYT, VectorType.RELYT,
VectorType.WEAVIATE, VectorType.WEAVIATE,
VectorType.ORACLE, VectorType.ORACLE,

@ -39,6 +39,7 @@ from .vdb.tencent_vector_config import TencentVectorDBConfig
from .vdb.tidb_on_qdrant_config import TidbOnQdrantConfig from .vdb.tidb_on_qdrant_config import TidbOnQdrantConfig
from .vdb.tidb_vector_config import TiDBVectorConfig from .vdb.tidb_vector_config import TiDBVectorConfig
from .vdb.upstash_config import UpstashConfig from .vdb.upstash_config import UpstashConfig
from .vdb.vastbase_vector_config import VastbaseVectorConfig
from .vdb.vikingdb_config import VikingDBConfig from .vdb.vikingdb_config import VikingDBConfig
from .vdb.weaviate_config import WeaviateConfig from .vdb.weaviate_config import WeaviateConfig
@ -270,6 +271,7 @@ class MiddlewareConfig(
OpenSearchConfig, OpenSearchConfig,
OracleConfig, OracleConfig,
PGVectorConfig, PGVectorConfig,
VastbaseVectorConfig,
PGVectoRSConfig, PGVectoRSConfig,
QdrantConfig, QdrantConfig,
RelytConfig, RelytConfig,

@ -32,3 +32,4 @@ class LindormConfig(BaseSettings):
description="Using UGC index will store the same type of Index in a single index but can retrieve separately.", description="Using UGC index will store the same type of Index in a single index but can retrieve separately.",
default=False, default=False,
) )
LINDORM_QUERY_TIMEOUT: Optional[float] = Field(description="The lindorm search request timeout (s)", default=2.0)

@ -0,0 +1,45 @@
from typing import Optional
from pydantic import Field, PositiveInt
from pydantic_settings import BaseSettings
class VastbaseVectorConfig(BaseSettings):
"""
Configuration settings for Vector (Vastbase with vector extension)
"""
VASTBASE_HOST: Optional[str] = Field(
description="Hostname or IP address of the Vastbase server with Vector extension (e.g., 'localhost')",
default=None,
)
VASTBASE_PORT: PositiveInt = Field(
description="Port number on which the Vastbase server is listening (default is 5432)",
default=5432,
)
VASTBASE_USER: Optional[str] = Field(
description="Username for authenticating with the Vastbase database",
default=None,
)
VASTBASE_PASSWORD: Optional[str] = Field(
description="Password for authenticating with the Vastbase database",
default=None,
)
VASTBASE_DATABASE: Optional[str] = Field(
description="Name of the Vastbase database to connect to",
default=None,
)
VASTBASE_MIN_CONNECTION: PositiveInt = Field(
description="Min connection of the Vastbase database",
default=1,
)
VASTBASE_MAX_CONNECTION: PositiveInt = Field(
description="Max connection of the Vastbase database",
default=5,
)

@ -657,6 +657,7 @@ class DatasetRetrievalSettingApi(Resource):
| VectorType.ELASTICSEARCH | VectorType.ELASTICSEARCH
| VectorType.ELASTICSEARCH_JA | VectorType.ELASTICSEARCH_JA
| VectorType.PGVECTOR | VectorType.PGVECTOR
| VectorType.VASTBASE
| VectorType.TIDB_ON_QDRANT | VectorType.TIDB_ON_QDRANT
| VectorType.LINDORM | VectorType.LINDORM
| VectorType.COUCHBASE | VectorType.COUCHBASE
@ -706,6 +707,7 @@ class DatasetRetrievalSettingMockApi(Resource):
| VectorType.ELASTICSEARCH_JA | VectorType.ELASTICSEARCH_JA
| VectorType.COUCHBASE | VectorType.COUCHBASE
| VectorType.PGVECTOR | VectorType.PGVECTOR
| VectorType.VASTBASE
| VectorType.LINDORM | VectorType.LINDORM
| VectorType.OPENGAUSS | VectorType.OPENGAUSS
| VectorType.OCEANBASE | VectorType.OCEANBASE

@ -14,6 +14,9 @@ from fields.conversation_fields import (
conversation_infinite_scroll_pagination_fields, conversation_infinite_scroll_pagination_fields,
simple_conversation_fields, simple_conversation_fields,
) )
from fields.conversation_variable_fields import (
conversation_variable_infinite_scroll_pagination_fields,
)
from libs.helper import uuid_value from libs.helper import uuid_value
from models.model import App, AppMode, EndUser from models.model import App, AppMode, EndUser
from services.conversation_service import ConversationService from services.conversation_service import ConversationService
@ -93,6 +96,31 @@ class ConversationRenameApi(Resource):
raise NotFound("Conversation Not Exists.") raise NotFound("Conversation Not Exists.")
class ConversationVariablesApi(Resource):
@validate_app_token(fetch_user_arg=FetchUserArg(fetch_from=WhereisUserArg.QUERY))
@marshal_with(conversation_variable_infinite_scroll_pagination_fields)
def get(self, app_model: App, end_user: EndUser, c_id):
# conversational variable only for chat app
app_mode = AppMode.value_of(app_model.mode)
if app_mode not in {AppMode.CHAT, AppMode.AGENT_CHAT, AppMode.ADVANCED_CHAT}:
raise NotChatAppError()
conversation_id = str(c_id)
parser = reqparse.RequestParser()
parser.add_argument("last_id", type=uuid_value, location="args")
parser.add_argument("limit", type=int_range(1, 100), required=False, default=20, location="args")
args = parser.parse_args()
try:
return ConversationService.get_conversational_variable(
app_model, conversation_id, end_user, args["limit"], args["last_id"]
)
except services.errors.conversation.ConversationNotExistsError:
raise NotFound("Conversation Not Exists.")
api.add_resource(ConversationRenameApi, "/conversations/<uuid:c_id>/name", endpoint="conversation_name") api.add_resource(ConversationRenameApi, "/conversations/<uuid:c_id>/name", endpoint="conversation_name")
api.add_resource(ConversationApi, "/conversations") api.add_resource(ConversationApi, "/conversations")
api.add_resource(ConversationDetailApi, "/conversations/<uuid:c_id>", endpoint="conversation_detail") api.add_resource(ConversationDetailApi, "/conversations/<uuid:c_id>", endpoint="conversation_detail")
api.add_resource(ConversationVariablesApi, "/conversations/<uuid:c_id>/variables", endpoint="conversation_variables")

@ -684,7 +684,9 @@ class AdvancedChatAppGenerateTaskPipeline:
) )
elif isinstance(event, QueueMessageReplaceEvent): elif isinstance(event, QueueMessageReplaceEvent):
# published by moderation # published by moderation
yield self._message_cycle_manager._message_replace_to_stream_response(answer=event.text) yield self._message_cycle_manager._message_replace_to_stream_response(
answer=event.text, reason=event.reason
)
elif isinstance(event, QueueAdvancedChatMessageEndEvent): elif isinstance(event, QueueAdvancedChatMessageEndEvent):
if not graph_runtime_state: if not graph_runtime_state:
raise ValueError("graph runtime state not initialized.") raise ValueError("graph runtime state not initialized.")
@ -695,7 +697,8 @@ class AdvancedChatAppGenerateTaskPipeline:
if output_moderation_answer: if output_moderation_answer:
self._task_state.answer = output_moderation_answer self._task_state.answer = output_moderation_answer
yield self._message_cycle_manager._message_replace_to_stream_response( yield self._message_cycle_manager._message_replace_to_stream_response(
answer=output_moderation_answer answer=output_moderation_answer,
reason=QueueMessageReplaceEvent.MessageReplaceReason.OUTPUT_MODERATION,
) )
# Save message # Save message

@ -264,8 +264,16 @@ class QueueMessageReplaceEvent(AppQueueEvent):
QueueMessageReplaceEvent entity QueueMessageReplaceEvent entity
""" """
class MessageReplaceReason(StrEnum):
"""
Reason for message replace event
"""
OUTPUT_MODERATION = "output_moderation"
event: QueueEvent = QueueEvent.MESSAGE_REPLACE event: QueueEvent = QueueEvent.MESSAGE_REPLACE
text: str text: str
reason: str
class QueueRetrieverResourcesEvent(AppQueueEvent): class QueueRetrieverResourcesEvent(AppQueueEvent):

@ -148,6 +148,7 @@ class MessageReplaceStreamResponse(StreamResponse):
event: StreamEvent = StreamEvent.MESSAGE_REPLACE event: StreamEvent = StreamEvent.MESSAGE_REPLACE
answer: str answer: str
reason: str
class AgentThoughtStreamResponse(StreamResponse): class AgentThoughtStreamResponse(StreamResponse):

@ -126,12 +126,12 @@ class BasedGenerateTaskPipeline:
if self._output_moderation_handler: if self._output_moderation_handler:
self._output_moderation_handler.stop_thread() self._output_moderation_handler.stop_thread()
completion = self._output_moderation_handler.moderation_completion( completion, flagged = self._output_moderation_handler.moderation_completion(
completion=completion, public_event=False completion=completion, public_event=False
) )
self._output_moderation_handler = None self._output_moderation_handler = None
if flagged:
return completion return completion
return None return None

@ -182,10 +182,12 @@ class MessageCycleManage:
from_variable_selector=from_variable_selector, from_variable_selector=from_variable_selector,
) )
def _message_replace_to_stream_response(self, answer: str) -> MessageReplaceStreamResponse: def _message_replace_to_stream_response(self, answer: str, reason: str = "") -> MessageReplaceStreamResponse:
""" """
Message replace to stream response. Message replace to stream response.
:param answer: answer :param answer: answer
:return: :return:
""" """
return MessageReplaceStreamResponse(task_id=self._application_generate_entity.task_id, answer=answer) return MessageReplaceStreamResponse(
task_id=self._application_generate_entity.task_id, answer=answer, reason=reason
)

@ -46,14 +46,14 @@ class OutputModeration(BaseModel):
if not self.thread: if not self.thread:
self.thread = self.start_thread() self.thread = self.start_thread()
def moderation_completion(self, completion: str, public_event: bool = False) -> str: def moderation_completion(self, completion: str, public_event: bool = False) -> tuple[str, bool]:
self.buffer = completion self.buffer = completion
self.is_final_chunk = True self.is_final_chunk = True
result = self.moderation(tenant_id=self.tenant_id, app_id=self.app_id, moderation_buffer=completion) result = self.moderation(tenant_id=self.tenant_id, app_id=self.app_id, moderation_buffer=completion)
if not result or not result.flagged: if not result or not result.flagged:
return completion return completion, False
if result.action == ModerationAction.DIRECT_OUTPUT: if result.action == ModerationAction.DIRECT_OUTPUT:
final_output = result.preset_response final_output = result.preset_response
@ -61,9 +61,14 @@ class OutputModeration(BaseModel):
final_output = result.text final_output = result.text
if public_event: if public_event:
self.queue_manager.publish(QueueMessageReplaceEvent(text=final_output), PublishFrom.TASK_PIPELINE) self.queue_manager.publish(
QueueMessageReplaceEvent(
text=final_output, reason=QueueMessageReplaceEvent.MessageReplaceReason.OUTPUT_MODERATION
),
PublishFrom.TASK_PIPELINE,
)
return final_output return final_output, True
def start_thread(self) -> threading.Thread: def start_thread(self) -> threading.Thread:
buffer_size = dify_config.MODERATION_BUFFER_SIZE buffer_size = dify_config.MODERATION_BUFFER_SIZE
@ -112,7 +117,12 @@ class OutputModeration(BaseModel):
# trigger replace event # trigger replace event
if self.thread_running: if self.thread_running:
self.queue_manager.publish(QueueMessageReplaceEvent(text=final_output), PublishFrom.TASK_PIPELINE) self.queue_manager.publish(
QueueMessageReplaceEvent(
text=final_output, reason=QueueMessageReplaceEvent.MessageReplaceReason.OUTPUT_MODERATION
),
PublishFrom.TASK_PIPELINE,
)
if result.action == ModerationAction.DIRECT_OUTPUT: if result.action == ModerationAction.DIRECT_OUTPUT:
break break

@ -32,6 +32,7 @@ class LindormVectorStoreConfig(BaseModel):
username: Optional[str] = None username: Optional[str] = None
password: Optional[str] = None password: Optional[str] = None
using_ugc: Optional[bool] = False using_ugc: Optional[bool] = False
request_timeout: Optional[float] = 1.0 # timeout units: s
@model_validator(mode="before") @model_validator(mode="before")
@classmethod @classmethod
@ -251,9 +252,9 @@ class LindormVectorStore(BaseVector):
query = default_vector_search_query(query_vector=query_vector, k=top_k, filters=filters, **kwargs) query = default_vector_search_query(query_vector=query_vector, k=top_k, filters=filters, **kwargs)
try: try:
params = {} params = {"timeout": self._client_config.request_timeout}
if self._using_ugc: if self._using_ugc:
params["routing"] = self._routing params["routing"] = self._routing # type: ignore
response = self._client.search(index=self._collection_name, body=query, params=params) response = self._client.search(index=self._collection_name, body=query, params=params)
except Exception: except Exception:
logger.exception(f"Error executing vector search, query: {query}") logger.exception(f"Error executing vector search, query: {query}")
@ -304,8 +305,8 @@ class LindormVectorStore(BaseVector):
routing=routing, routing=routing,
routing_field=self._routing_field, routing_field=self._routing_field,
) )
params = {"timeout": self._client_config.request_timeout}
response = self._client.search(index=self._collection_name, body=full_text_query) response = self._client.search(index=self._collection_name, body=full_text_query, params=params)
docs = [] docs = []
for hit in response["hits"]["hits"]: for hit in response["hits"]["hits"]:
docs.append( docs.append(
@ -554,6 +555,7 @@ class LindormVectorStoreFactory(AbstractVectorFactory):
username=dify_config.LINDORM_USERNAME, username=dify_config.LINDORM_USERNAME,
password=dify_config.LINDORM_PASSWORD, password=dify_config.LINDORM_PASSWORD,
using_ugc=dify_config.USING_UGC_INDEX, using_ugc=dify_config.USING_UGC_INDEX,
request_timeout=dify_config.LINDORM_QUERY_TIMEOUT,
) )
using_ugc = dify_config.USING_UGC_INDEX using_ugc = dify_config.USING_UGC_INDEX
if using_ugc is None: if using_ugc is None:

@ -0,0 +1,243 @@
import json
import uuid
from contextlib import contextmanager
from typing import Any
import psycopg2.extras # type: ignore
import psycopg2.pool # type: ignore
from pydantic import BaseModel, model_validator
from configs import dify_config
from core.rag.datasource.vdb.vector_base import BaseVector
from core.rag.datasource.vdb.vector_factory import AbstractVectorFactory
from core.rag.datasource.vdb.vector_type import VectorType
from core.rag.embedding.embedding_base import Embeddings
from core.rag.models.document import Document
from extensions.ext_redis import redis_client
from models.dataset import Dataset
class VastbaseVectorConfig(BaseModel):
host: str
port: int
user: str
password: str
database: str
min_connection: int
max_connection: int
@model_validator(mode="before")
@classmethod
def validate_config(cls, values: dict) -> dict:
if not values["host"]:
raise ValueError("config VASTBASE_HOST is required")
if not values["port"]:
raise ValueError("config VASTBASE_PORT is required")
if not values["user"]:
raise ValueError("config VASTBASE_USER is required")
if not values["password"]:
raise ValueError("config VASTBASE_PASSWORD is required")
if not values["database"]:
raise ValueError("config VASTBASE_DATABASE is required")
if not values["min_connection"]:
raise ValueError("config VASTBASE_MIN_CONNECTION is required")
if not values["max_connection"]:
raise ValueError("config VASTBASE_MAX_CONNECTION is required")
if values["min_connection"] > values["max_connection"]:
raise ValueError("config VASTBASE_MIN_CONNECTION should less than VASTBASE_MAX_CONNECTION")
return values
SQL_CREATE_TABLE = """
CREATE TABLE IF NOT EXISTS {table_name} (
id UUID PRIMARY KEY,
text TEXT NOT NULL,
meta JSONB NOT NULL,
embedding floatvector({dimension}) NOT NULL
);
"""
SQL_CREATE_INDEX = """
CREATE INDEX IF NOT EXISTS embedding_cosine_v1_idx ON {table_name}
USING hnsw (embedding floatvector_cosine_ops) WITH (m = 16, ef_construction = 64);
"""
class VastbaseVector(BaseVector):
def __init__(self, collection_name: str, config: VastbaseVectorConfig):
super().__init__(collection_name)
self.pool = self._create_connection_pool(config)
self.table_name = f"embedding_{collection_name}"
def get_type(self) -> str:
return VectorType.VASTBASE
def _create_connection_pool(self, config: VastbaseVectorConfig):
return psycopg2.pool.SimpleConnectionPool(
config.min_connection,
config.max_connection,
host=config.host,
port=config.port,
user=config.user,
password=config.password,
database=config.database,
)
@contextmanager
def _get_cursor(self):
conn = self.pool.getconn()
cur = conn.cursor()
try:
yield cur
finally:
cur.close()
conn.commit()
self.pool.putconn(conn)
def create(self, texts: list[Document], embeddings: list[list[float]], **kwargs):
dimension = len(embeddings[0])
self._create_collection(dimension)
return self.add_texts(texts, embeddings)
def add_texts(self, documents: list[Document], embeddings: list[list[float]], **kwargs):
values = []
pks = []
for i, doc in enumerate(documents):
if doc.metadata is not None:
doc_id = doc.metadata.get("doc_id", str(uuid.uuid4()))
pks.append(doc_id)
values.append(
(
doc_id,
doc.page_content,
json.dumps(doc.metadata),
embeddings[i],
)
)
with self._get_cursor() as cur:
psycopg2.extras.execute_values(
cur, f"INSERT INTO {self.table_name} (id, text, meta, embedding) VALUES %s", values
)
return pks
def text_exists(self, id: str) -> bool:
with self._get_cursor() as cur:
cur.execute(f"SELECT id FROM {self.table_name} WHERE id = %s", (id,))
return cur.fetchone() is not None
def get_by_ids(self, ids: list[str]) -> list[Document]:
with self._get_cursor() as cur:
cur.execute(f"SELECT meta, text FROM {self.table_name} WHERE id IN %s", (tuple(ids),))
docs = []
for record in cur:
docs.append(Document(page_content=record[1], metadata=record[0]))
return docs
def delete_by_ids(self, ids: list[str]) -> None:
# Avoiding crashes caused by performing delete operations on empty lists in certain scenarios
# Scenario 1: extract a document fails, resulting in a table not being created.
# Then clicking the retry button triggers a delete operation on an empty list.
if not ids:
return
with self._get_cursor() as cur:
cur.execute(f"DELETE FROM {self.table_name} WHERE id IN %s", (tuple(ids),))
def delete_by_metadata_field(self, key: str, value: str) -> None:
with self._get_cursor() as cur:
cur.execute(f"DELETE FROM {self.table_name} WHERE meta->>%s = %s", (key, value))
def search_by_vector(self, query_vector: list[float], **kwargs: Any) -> list[Document]:
"""
Search the nearest neighbors to a vector.
:param query_vector: The input vector to search for similar items.
:param top_k: The number of nearest neighbors to return, default is 5.
:return: List of Documents that are nearest to the query vector.
"""
top_k = kwargs.get("top_k", 4)
if not isinstance(top_k, int) or top_k <= 0:
raise ValueError("top_k must be a positive integer")
with self._get_cursor() as cur:
cur.execute(
f"SELECT meta, text, embedding <=> %s AS distance FROM {self.table_name}"
f" ORDER BY distance LIMIT {top_k}",
(json.dumps(query_vector),),
)
docs = []
score_threshold = float(kwargs.get("score_threshold") or 0.0)
for record in cur:
metadata, text, distance = record
score = 1 - distance
metadata["score"] = score
if score > score_threshold:
docs.append(Document(page_content=text, metadata=metadata))
return docs
def search_by_full_text(self, query: str, **kwargs: Any) -> list[Document]:
top_k = kwargs.get("top_k", 5)
if not isinstance(top_k, int) or top_k <= 0:
raise ValueError("top_k must be a positive integer")
with self._get_cursor() as cur:
cur.execute(
f"""SELECT meta, text, ts_rank(to_tsvector(coalesce(text, '')), plainto_tsquery(%s)) AS score
FROM {self.table_name}
WHERE to_tsvector(text) @@ plainto_tsquery(%s)
ORDER BY score DESC
LIMIT {top_k}""",
# f"'{query}'" is required in order to account for whitespace in query
(f"'{query}'", f"'{query}'"),
)
docs = []
for record in cur:
metadata, text, score = record
metadata["score"] = score
docs.append(Document(page_content=text, metadata=metadata))
return docs
def delete(self) -> None:
with self._get_cursor() as cur:
cur.execute(f"DROP TABLE IF EXISTS {self.table_name}")
def _create_collection(self, dimension: int):
cache_key = f"vector_indexing_{self._collection_name}"
lock_name = f"{cache_key}_lock"
with redis_client.lock(lock_name, timeout=20):
collection_exist_cache_key = f"vector_indexing_{self._collection_name}"
if redis_client.get(collection_exist_cache_key):
return
with self._get_cursor() as cur:
cur.execute(SQL_CREATE_TABLE.format(table_name=self.table_name, dimension=dimension))
# Vastbase 支持的向量维度取值范围为 [1,16000]
if dimension <= 16000:
cur.execute(SQL_CREATE_INDEX.format(table_name=self.table_name))
redis_client.set(collection_exist_cache_key, 1, ex=3600)
class VastbaseVectorFactory(AbstractVectorFactory):
def init_vector(self, dataset: Dataset, attributes: list, embeddings: Embeddings) -> VastbaseVector:
if dataset.index_struct_dict:
class_prefix: str = dataset.index_struct_dict["vector_store"]["class_prefix"]
collection_name = class_prefix
else:
dataset_id = dataset.id
collection_name = Dataset.gen_collection_name_by_id(dataset_id)
dataset.index_struct = json.dumps(self.gen_index_struct_dict(VectorType.VASTBASE, collection_name))
return VastbaseVector(
collection_name=collection_name,
config=VastbaseVectorConfig(
host=dify_config.VASTBASE_HOST or "localhost",
port=dify_config.VASTBASE_PORT,
user=dify_config.VASTBASE_USER or "dify",
password=dify_config.VASTBASE_PASSWORD or "",
database=dify_config.VASTBASE_DATABASE or "dify",
min_connection=dify_config.VASTBASE_MIN_CONNECTION,
max_connection=dify_config.VASTBASE_MAX_CONNECTION,
),
)

@ -74,6 +74,10 @@ class Vector:
from core.rag.datasource.vdb.pgvector.pgvector import PGVectorFactory from core.rag.datasource.vdb.pgvector.pgvector import PGVectorFactory
return PGVectorFactory return PGVectorFactory
case VectorType.VASTBASE:
from core.rag.datasource.vdb.pyvastbase.vastbase_vector import VastbaseVectorFactory
return VastbaseVectorFactory
case VectorType.PGVECTO_RS: case VectorType.PGVECTO_RS:
from core.rag.datasource.vdb.pgvecto_rs.pgvecto_rs import PGVectoRSFactory from core.rag.datasource.vdb.pgvecto_rs.pgvecto_rs import PGVectoRSFactory

@ -7,7 +7,9 @@ class VectorType(StrEnum):
MILVUS = "milvus" MILVUS = "milvus"
MYSCALE = "myscale" MYSCALE = "myscale"
PGVECTOR = "pgvector" PGVECTOR = "pgvector"
VASTBASE = "vastbase"
PGVECTO_RS = "pgvecto-rs" PGVECTO_RS = "pgvecto-rs"
QDRANT = "qdrant" QDRANT = "qdrant"
RELYT = "relyt" RELYT = "relyt"
TIDB_VECTOR = "tidb_vector" TIDB_VECTOR = "tidb_vector"

@ -35,8 +35,9 @@ class BuiltinToolProviderController(ToolProviderController):
provider_yaml["credentials_for_provider"][credential_name]["name"] = credential_name provider_yaml["credentials_for_provider"][credential_name]["name"] = credential_name
credentials_schema = [] credentials_schema = []
for credential in provider_yaml.get("credentials_for_provider", {}).values(): for credential in provider_yaml.get("credentials_for_provider", {}):
credentials_schema.append(credential) credential_dict = provider_yaml.get("credentials_for_provider", {}).get(credential, {})
credentials_schema.append(credential_dict)
super().__init__( super().__init__(
entity=ToolProviderEntity( entity=ToolProviderEntity(

@ -19,3 +19,9 @@ paginated_conversation_variable_fields = {
"has_more": fields.Boolean, "has_more": fields.Boolean,
"data": fields.List(fields.Nested(conversation_variable_fields), attribute="data"), "data": fields.List(fields.Nested(conversation_variable_fields), attribute="data"),
} }
conversation_variable_infinite_scroll_pagination_fields = {
"limit": fields.Integer,
"has_more": fields.Boolean,
"data": fields.List(fields.Nested(conversation_variable_fields)),
}

@ -1,6 +1,6 @@
[project] [project]
name = "dify-api" name = "dify-api"
version = "1.2.0" version = "1.3.0"
requires-python = ">=3.11,<3.13" requires-python = ">=3.11,<3.13"
dependencies = [ dependencies = [

@ -9,9 +9,14 @@ from core.app.entities.app_invoke_entities import InvokeFrom
from core.llm_generator.llm_generator import LLMGenerator from core.llm_generator.llm_generator import LLMGenerator
from extensions.ext_database import db from extensions.ext_database import db
from libs.infinite_scroll_pagination import InfiniteScrollPagination from libs.infinite_scroll_pagination import InfiniteScrollPagination
from models import ConversationVariable
from models.account import Account from models.account import Account
from models.model import App, Conversation, EndUser, Message from models.model import App, Conversation, EndUser, Message
from services.errors.conversation import ConversationNotExistsError, LastConversationNotExistsError from services.errors.conversation import (
ConversationNotExistsError,
ConversationVariableNotExistsError,
LastConversationNotExistsError,
)
from services.errors.message import MessageNotExistsError from services.errors.message import MessageNotExistsError
@ -166,3 +171,50 @@ class ConversationService:
conversation.is_deleted = True conversation.is_deleted = True
conversation.updated_at = datetime.now(UTC).replace(tzinfo=None) conversation.updated_at = datetime.now(UTC).replace(tzinfo=None)
db.session.commit() db.session.commit()
@classmethod
def get_conversational_variable(
cls,
app_model: App,
conversation_id: str,
user: Optional[Union[Account, EndUser]],
limit: int,
last_id: Optional[str],
) -> InfiniteScrollPagination:
conversation = cls.get_conversation(app_model, conversation_id, user)
stmt = (
select(ConversationVariable)
.where(ConversationVariable.app_id == app_model.id)
.where(ConversationVariable.conversation_id == conversation.id)
.order_by(ConversationVariable.created_at)
)
with Session(db.engine) as session:
if last_id:
last_variable = session.scalar(stmt.where(ConversationVariable.id == last_id))
if not last_variable:
raise ConversationVariableNotExistsError()
# Filter for variables created after the last_id
stmt = stmt.where(ConversationVariable.created_at > last_variable.created_at)
# Apply limit to query
query_stmt = stmt.limit(limit) # Get one extra to check if there are more
rows = session.scalars(query_stmt).all()
has_more = False
if len(rows) > limit:
has_more = True
rows = rows[:limit] # Remove the extra item
variables = [
{
"created_at": row.created_at,
"updated_at": row.updated_at,
**row.to_variable().model_dump(),
}
for row in rows
]
return InfiniteScrollPagination(variables, limit, has_more)

@ -11,3 +11,7 @@ class ConversationNotExistsError(BaseServiceError):
class ConversationCompletedError(Exception): class ConversationCompletedError(Exception):
pass pass
class ConversationVariableNotExistsError(BaseServiceError):
pass

@ -0,0 +1,27 @@
from core.rag.datasource.vdb.pyvastbase.vastbase_vector import VastbaseVector, VastbaseVectorConfig
from tests.integration_tests.vdb.test_vector_store import (
AbstractVectorTest,
get_example_text,
setup_mock_redis,
)
class VastbaseVectorTest(AbstractVectorTest):
def __init__(self):
super().__init__()
self.vector = VastbaseVector(
collection_name=self.collection_name,
config=VastbaseVectorConfig(
host="localhost",
port=5434,
user="dify",
password="Difyai123456",
database="dify",
min_connection=1,
max_connection=5,
),
)
def test_vastbase_vector(setup_mock_redis):
VastbaseVectorTest().run_all_tests()

@ -1148,7 +1148,7 @@ wheels = [
[[package]] [[package]]
name = "dify-api" name = "dify-api"
version = "1.2.0" version = "1.3.0"
source = { virtual = "." } source = { virtual = "." }
dependencies = [ dependencies = [
{ name = "authlib" }, { name = "authlib" },

@ -406,6 +406,7 @@ QDRANT_GRPC_PORT=6334
# Milvus configuration. Only available when VECTOR_STORE is `milvus`. # Milvus configuration. Only available when VECTOR_STORE is `milvus`.
# The milvus uri. # The milvus uri.
MILVUS_URI=http://host.docker.internal:19530 MILVUS_URI=http://host.docker.internal:19530
MILVUS_DATABASE=
MILVUS_TOKEN= MILVUS_TOKEN=
MILVUS_USER= MILVUS_USER=
MILVUS_PASSWORD= MILVUS_PASSWORD=
@ -441,6 +442,15 @@ PGVECTOR_MAX_CONNECTION=5
PGVECTOR_PG_BIGM=false PGVECTOR_PG_BIGM=false
PGVECTOR_PG_BIGM_VERSION=1.2-20240606 PGVECTOR_PG_BIGM_VERSION=1.2-20240606
# vastbase configurations, only available when VECTOR_STORE is `vastbase`
VASTBASE_HOST=vastbase
VASTBASE_PORT=5432
VASTBASE_USER=dify
VASTBASE_PASSWORD=Difyai123456
VASTBASE_DATABASE=dify
VASTBASE_MIN_CONNECTION=1
VASTBASE_MAX_CONNECTION=5
# pgvecto-rs configurations, only available when VECTOR_STORE is `pgvecto-rs` # pgvecto-rs configurations, only available when VECTOR_STORE is `pgvecto-rs`
PGVECTO_RS_HOST=pgvecto-rs PGVECTO_RS_HOST=pgvecto-rs
PGVECTO_RS_PORT=5432 PGVECTO_RS_PORT=5432
@ -553,6 +563,7 @@ VIKINGDB_SOCKET_TIMEOUT=30
LINDORM_URL=http://lindorm:30070 LINDORM_URL=http://lindorm:30070
LINDORM_USERNAME=lindorm LINDORM_USERNAME=lindorm
LINDORM_PASSWORD=lindorm LINDORM_PASSWORD=lindorm
LINDORM_QUERY_TIMEOUT=1
# OceanBase Vector configuration, only available when VECTOR_STORE is `oceanbase` # OceanBase Vector configuration, only available when VECTOR_STORE is `oceanbase`
OCEANBASE_VECTOR_HOST=oceanbase OCEANBASE_VECTOR_HOST=oceanbase

@ -142,7 +142,7 @@ services:
# plugin daemon # plugin daemon
plugin_daemon: plugin_daemon:
image: langgenius/dify-plugin-daemon:0.0.8-local image: langgenius/dify-plugin-daemon:0.0.9-local
restart: always restart: always
environment: environment:
# Use the shared environment variables. # Use the shared environment variables.
@ -363,6 +363,30 @@ services:
timeout: 3s timeout: 3s
retries: 30 retries: 30
# get image from https://www.vastdata.com.cn/
vastbase:
image: vastdata/vastbase-vector
profiles:
- vastbase
restart: always
environment:
- VB_DBCOMPATIBILITY=PG
- VB_DB=dify
- VB_USERNAME=dify
- VB_PASSWORD=Difyai123456
ports:
- '5434:5432'
volumes:
- ./vastbase/lic:/home/vastbase/vastbase/lic
- ./vastbase/data:/home/vastbase/data
- ./vastbase/backup:/home/vastbase/backup
- ./vastbase/backup_log:/home/vastbase/backup_log
healthcheck:
test: [ 'CMD', 'pg_isready' ]
interval: 1s
timeout: 3s
retries: 30
# pgvecto-rs vector store # pgvecto-rs vector store
pgvecto-rs: pgvecto-rs:
image: tensorchord/pgvecto-rs:pg16-v0.3.0 image: tensorchord/pgvecto-rs:pg16-v0.3.0

@ -71,7 +71,7 @@ services:
# plugin daemon # plugin daemon
plugin_daemon: plugin_daemon:
image: langgenius/dify-plugin-daemon:0.0.8-local image: langgenius/dify-plugin-daemon:0.0.9-local
restart: always restart: always
env_file: env_file:
- ./middleware.env - ./middleware.env

@ -138,6 +138,7 @@ x-shared-env: &shared-api-worker-env
QDRANT_GRPC_ENABLED: ${QDRANT_GRPC_ENABLED:-false} QDRANT_GRPC_ENABLED: ${QDRANT_GRPC_ENABLED:-false}
QDRANT_GRPC_PORT: ${QDRANT_GRPC_PORT:-6334} QDRANT_GRPC_PORT: ${QDRANT_GRPC_PORT:-6334}
MILVUS_URI: ${MILVUS_URI:-http://host.docker.internal:19530} MILVUS_URI: ${MILVUS_URI:-http://host.docker.internal:19530}
MILVUS_DATABASE: ${MILVUS_DATABASE:-}
MILVUS_TOKEN: ${MILVUS_TOKEN:-} MILVUS_TOKEN: ${MILVUS_TOKEN:-}
MILVUS_USER: ${MILVUS_USER:-} MILVUS_USER: ${MILVUS_USER:-}
MILVUS_PASSWORD: ${MILVUS_PASSWORD:-} MILVUS_PASSWORD: ${MILVUS_PASSWORD:-}
@ -163,6 +164,13 @@ x-shared-env: &shared-api-worker-env
PGVECTOR_MAX_CONNECTION: ${PGVECTOR_MAX_CONNECTION:-5} PGVECTOR_MAX_CONNECTION: ${PGVECTOR_MAX_CONNECTION:-5}
PGVECTOR_PG_BIGM: ${PGVECTOR_PG_BIGM:-false} PGVECTOR_PG_BIGM: ${PGVECTOR_PG_BIGM:-false}
PGVECTOR_PG_BIGM_VERSION: ${PGVECTOR_PG_BIGM_VERSION:-1.2-20240606} PGVECTOR_PG_BIGM_VERSION: ${PGVECTOR_PG_BIGM_VERSION:-1.2-20240606}
VASTBASE_HOST: ${VASTBASE_HOST:-vastbase}
VASTBASE_PORT: ${VASTBASE_PORT:-5432}
VASTBASE_USER: ${VASTBASE_USER:-dify}
VASTBASE_PASSWORD: ${VASTBASE_PASSWORD:-Difyai123456}
VASTBASE_DATABASE: ${VASTBASE_DATABASE:-dify}
VASTBASE_MIN_CONNECTION: ${VASTBASE_MIN_CONNECTION:-1}
VASTBASE_MAX_CONNECTION: ${VASTBASE_MAX_CONNECTION:-5}
PGVECTO_RS_HOST: ${PGVECTO_RS_HOST:-pgvecto-rs} PGVECTO_RS_HOST: ${PGVECTO_RS_HOST:-pgvecto-rs}
PGVECTO_RS_PORT: ${PGVECTO_RS_PORT:-5432} PGVECTO_RS_PORT: ${PGVECTO_RS_PORT:-5432}
PGVECTO_RS_USER: ${PGVECTO_RS_USER:-postgres} PGVECTO_RS_USER: ${PGVECTO_RS_USER:-postgres}
@ -250,6 +258,7 @@ x-shared-env: &shared-api-worker-env
LINDORM_URL: ${LINDORM_URL:-http://lindorm:30070} LINDORM_URL: ${LINDORM_URL:-http://lindorm:30070}
LINDORM_USERNAME: ${LINDORM_USERNAME:-lindorm} LINDORM_USERNAME: ${LINDORM_USERNAME:-lindorm}
LINDORM_PASSWORD: ${LINDORM_PASSWORD:-lindorm} LINDORM_PASSWORD: ${LINDORM_PASSWORD:-lindorm}
LINDORM_QUERY_TIMEOUT: ${LINDORM_QUERY_TIMEOUT:-1}
OCEANBASE_VECTOR_HOST: ${OCEANBASE_VECTOR_HOST:-oceanbase} OCEANBASE_VECTOR_HOST: ${OCEANBASE_VECTOR_HOST:-oceanbase}
OCEANBASE_VECTOR_PORT: ${OCEANBASE_VECTOR_PORT:-2881} OCEANBASE_VECTOR_PORT: ${OCEANBASE_VECTOR_PORT:-2881}
OCEANBASE_VECTOR_USER: ${OCEANBASE_VECTOR_USER:-root@test} OCEANBASE_VECTOR_USER: ${OCEANBASE_VECTOR_USER:-root@test}
@ -619,7 +628,7 @@ services:
# plugin daemon # plugin daemon
plugin_daemon: plugin_daemon:
image: langgenius/dify-plugin-daemon:0.0.8-local image: langgenius/dify-plugin-daemon:0.0.9-local
restart: always restart: always
environment: environment:
# Use the shared environment variables. # Use the shared environment variables.
@ -840,6 +849,30 @@ services:
timeout: 3s timeout: 3s
retries: 30 retries: 30
# get image from https://www.vastdata.com.cn/
vastbase:
image: vastdata/vastbase-vector
profiles:
- vastbase
restart: always
environment:
- VB_DBCOMPATIBILITY=PG
- VB_DB=dify
- VB_USERNAME=dify
- VB_PASSWORD=Difyai123456
ports:
- '5434:5432'
volumes:
- ./vastbase/lic:/home/vastbase/vastbase/lic
- ./vastbase/data:/home/vastbase/data
- ./vastbase/backup:/home/vastbase/backup
- ./vastbase/backup_log:/home/vastbase/backup_log
healthcheck:
test: [ 'CMD', 'pg_isready' ]
interval: 1s
timeout: 3s
retries: 30
# pgvecto-rs vector store # pgvecto-rs vector store
pgvecto-rs: pgvecto-rs:
image: tensorchord/pgvecto-rs:pg16-v0.3.0 image: tensorchord/pgvecto-rs:pg16-v0.3.0

@ -14,6 +14,7 @@ import Loading from '@/app/components/base/loading'
import Badge from '@/app/components/base/badge' import Badge from '@/app/components/base/badge'
import { useKnowledge } from '@/hooks/use-knowledge' import { useKnowledge } from '@/hooks/use-knowledge'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { basePath } from '@/utils/var'
export type ISelectDataSetProps = { export type ISelectDataSetProps = {
isShow: boolean isShow: boolean
@ -111,7 +112,7 @@ const SelectDataSet: FC<ISelectDataSetProps> = ({
}} }}
> >
<span className='text-text-tertiary'>{t('appDebug.feature.dataSet.noDataSet')}</span> <span className='text-text-tertiary'>{t('appDebug.feature.dataSet.noDataSet')}</span>
<Link href="/datasets/create" className='font-normal text-text-accent'>{t('appDebug.feature.dataSet.toCreate')}</Link> <Link href={`${basePath}/datasets/create`} className='font-normal text-text-accent'>{t('appDebug.feature.dataSet.toCreate')}</Link>
</div> </div>
)} )}

@ -29,7 +29,7 @@ const OPTION_MAP = {
iframe: { iframe: {
getContent: (url: string, token: string) => getContent: (url: string, token: string) =>
`<iframe `<iframe
src="${url}${basePath}/chat/${token}" src="${url}${basePath}/chatbot/${token}"
style="width: 100%; height: 100%; min-height: 700px" style="width: 100%; height: 100%; min-height: 700px"
frameborder="0" frameborder="0"
allow="microphone"> allow="microphone">

@ -1,4 +1,5 @@
import type { FC } from 'react' import type { FC } from 'react'
import { basePath } from '@/utils/var'
type LogoEmbeddedChatAvatarProps = { type LogoEmbeddedChatAvatarProps = {
className?: string className?: string
@ -8,7 +9,7 @@ const LogoEmbeddedChatAvatar: FC<LogoEmbeddedChatAvatarProps> = ({
}) => { }) => {
return ( return (
<img <img
src='/logo/logo-embedded-chat-avatar.png' src={`${basePath}/logo/logo-embedded-chat-avatar.png`}
className={`block h-10 w-10 ${className}`} className={`block h-10 w-10 ${className}`}
alt='logo' alt='logo'
/> />

@ -144,7 +144,7 @@ const WorkflowVariableBlockComponent = ({
} }
if (!node) if (!node)
return null return Item
return ( return (
<Tooltip <Tooltip

@ -1,3 +1,4 @@
import type { BasicPlan } from '@/app/components/billing/type'
import { Plan, type PlanInfo, Priority } from '@/app/components/billing/type' import { Plan, type PlanInfo, Priority } from '@/app/components/billing/type'
const supportModelProviders = 'OpenAI/Anthropic/Llama2/Azure OpenAI/Hugging Face/Replicate' const supportModelProviders = 'OpenAI/Anthropic/Llama2/Azure OpenAI/Hugging Face/Replicate'
@ -10,7 +11,7 @@ export const contactSalesUrl = 'https://vikgc6bnu1s.typeform.com/dify-business'
export const getStartedWithCommunityUrl = 'https://github.com/langgenius/dify' export const getStartedWithCommunityUrl = 'https://github.com/langgenius/dify'
export const getWithPremiumUrl = 'https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6' export const getWithPremiumUrl = 'https://aws.amazon.com/marketplace/pp/prodview-t22mebxzwjhu6'
export const ALL_PLANS: Record<Plan, PlanInfo> = { export const ALL_PLANS: Record<BasicPlan, PlanInfo> = {
sandbox: { sandbox: {
level: 1, level: 1,
price: 0, price: 0,
@ -22,6 +23,7 @@ export const ALL_PLANS: Record<Plan, PlanInfo> = {
vectorSpace: '50MB', vectorSpace: '50MB',
documentsUploadQuota: 0, documentsUploadQuota: 0,
documentsRequestQuota: 10, documentsRequestQuota: 10,
apiRateLimit: 5000,
documentProcessingPriority: Priority.standard, documentProcessingPriority: Priority.standard,
messageRequest: 200, messageRequest: 200,
annotatedResponse: 10, annotatedResponse: 10,
@ -38,6 +40,7 @@ export const ALL_PLANS: Record<Plan, PlanInfo> = {
vectorSpace: '5GB', vectorSpace: '5GB',
documentsUploadQuota: 0, documentsUploadQuota: 0,
documentsRequestQuota: 100, documentsRequestQuota: 100,
apiRateLimit: NUM_INFINITE,
documentProcessingPriority: Priority.priority, documentProcessingPriority: Priority.priority,
messageRequest: 5000, messageRequest: 5000,
annotatedResponse: 2000, annotatedResponse: 2000,
@ -54,6 +57,7 @@ export const ALL_PLANS: Record<Plan, PlanInfo> = {
vectorSpace: '20GB', vectorSpace: '20GB',
documentsUploadQuota: 0, documentsUploadQuota: 0,
documentsRequestQuota: 1000, documentsRequestQuota: 1000,
apiRateLimit: NUM_INFINITE,
documentProcessingPriority: Priority.topPriority, documentProcessingPriority: Priority.topPriority,
messageRequest: 10000, messageRequest: 10000,
annotatedResponse: 5000, annotatedResponse: 5000,
@ -62,7 +66,7 @@ export const ALL_PLANS: Record<Plan, PlanInfo> = {
} }
export const defaultPlan = { export const defaultPlan = {
type: Plan.sandbox, type: Plan.sandbox as BasicPlan,
usage: { usage: {
documents: 50, documents: 50,
vectorSpace: 1, vectorSpace: 1,

@ -2,7 +2,8 @@
import type { FC, ReactNode } from 'react' import type { FC, ReactNode } from 'react'
import React from 'react' import React from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { RiApps2Line, RiBook2Line, RiBrain2Line, RiChatAiLine, RiFileEditLine, RiFolder6Line, RiGroupLine, RiHardDrive3Line, RiHistoryLine, RiProgress3Line, RiQuestionLine, RiSeoLine } from '@remixicon/react' import { RiApps2Line, RiBook2Line, RiBrain2Line, RiChatAiLine, RiFileEditLine, RiFolder6Line, RiGroupLine, RiHardDrive3Line, RiHistoryLine, RiProgress3Line, RiQuestionLine, RiSeoLine, RiTerminalBoxLine } from '@remixicon/react'
import type { BasicPlan } from '../type'
import { Plan } from '../type' import { Plan } from '../type'
import { ALL_PLANS, NUM_INFINITE } from '../config' import { ALL_PLANS, NUM_INFINITE } from '../config'
import Toast from '../../base/toast' import Toast from '../../base/toast'
@ -15,8 +16,8 @@ import { useAppContext } from '@/context/app-context'
import { fetchSubscriptionUrls } from '@/service/billing' import { fetchSubscriptionUrls } from '@/service/billing'
type Props = { type Props = {
currentPlan: Plan currentPlan: BasicPlan
plan: Plan plan: BasicPlan
planRange: PlanRange planRange: PlanRange
canPay: boolean canPay: boolean
} }
@ -127,8 +128,8 @@ const PlanItem: FC<Props> = ({
<div className='flex flex-col gap-y-1'> <div className='flex flex-col gap-y-1'>
{style[plan].icon} {style[plan].icon}
<div className='flex items-center'> <div className='flex items-center'>
<div className='text-lg font-semibold uppercase leading-[125%] text-text-primary'>{t(`${i18nPrefix}.name`)}</div> <div className='grow text-lg font-semibold uppercase leading-[125%] text-text-primary'>{t(`${i18nPrefix}.name`)}</div>
{isMostPopularPlan && <div className='ml-1 flex items-center justify-center rounded-full border-[0.5px] bg-price-premium-badge-background px-1 py-[3px] text-components-premium-badge-grey-text-stop-0 shadow-xs'> {isMostPopularPlan && <div className='ml-1 flex shrink-0 items-center justify-center rounded-full border-[0.5px] bg-price-premium-badge-background px-1 py-[3px] text-components-premium-badge-grey-text-stop-0 shadow-xs'>
<div className='pl-0.5'> <div className='pl-0.5'>
<SparklesSoft className='size-3' /> <SparklesSoft className='size-3' />
</div> </div>
@ -205,6 +206,14 @@ const PlanItem: FC<Props> = ({
label={t('billing.plansCommon.documentsRequestQuota', { count: planInfo.documentsRequestQuota })} label={t('billing.plansCommon.documentsRequestQuota', { count: planInfo.documentsRequestQuota })}
tooltip={t('billing.plansCommon.documentsRequestQuotaTooltip')} tooltip={t('billing.plansCommon.documentsRequestQuotaTooltip')}
/> />
<KeyValue
icon={<RiTerminalBoxLine />}
label={
planInfo.apiRateLimit === NUM_INFINITE ? `${t('billing.plansCommon.unlimitedApiRate')}`
: `${t('billing.plansCommon.apiRateLimitUnit', { count: planInfo.apiRateLimit })} ${t('billing.plansCommon.apiRateLimit')}`
}
tooltip={planInfo.apiRateLimit === NUM_INFINITE ? null : t('billing.plansCommon.apiRateLimitTooltip') as string}
/>
<KeyValue <KeyValue
icon={<RiProgress3Line />} icon={<RiProgress3Line />}
label={[t(`billing.plansCommon.priority.${planInfo.documentProcessingPriority}`), t('billing.plansCommon.documentProcessingPriority')].join('')} label={[t(`billing.plansCommon.priority.${planInfo.documentProcessingPriority}`), t('billing.plansCommon.documentProcessingPriority')].join('')}

@ -9,6 +9,9 @@ export enum Priority {
priority = 'priority', priority = 'priority',
topPriority = 'top-priority', topPriority = 'top-priority',
} }
export type BasicPlan = Plan.sandbox | Plan.professional | Plan.team
export type PlanInfo = { export type PlanInfo = {
level: number level: number
price: number price: number
@ -20,6 +23,7 @@ export type PlanInfo = {
vectorSpace: string vectorSpace: string
documentsUploadQuota: number documentsUploadQuota: number
documentsRequestQuota: number documentsRequestQuota: number
apiRateLimit: number
documentProcessingPriority: Priority documentProcessingPriority: Priority
logHistory: number logHistory: number
messageRequest: number messageRequest: number
@ -60,7 +64,7 @@ export type CurrentPlanInfoBackend = {
billing: { billing: {
enabled: boolean enabled: boolean
subscription: { subscription: {
plan: Plan plan: BasicPlan
} }
} }
members: { members: {

@ -915,6 +915,106 @@ Chat applications support session persistence, allowing previous chat history to
--- ---
<Heading
url='/conversations/:conversation_id/variables'
method='GET'
title='Get Conversation Variables'
name='#conversation-variables'
/>
<Row>
<Col>
Retrieve variables from a specific conversation. This endpoint is useful for extracting structured data that was captured during the conversation.
### Path Parameters
<Properties>
<Property name='conversation_id' type='string' key='conversation_id'>
The ID of the conversation to retrieve variables from.
</Property>
</Properties>
### Query Parameters
<Properties>
<Property name='user' type='string' key='user'>
The user identifier, defined by the developer, must ensure uniqueness within the application
</Property>
<Property name='last_id' type='string' key='last_id'>
(Optional) The ID of the last record on the current page, default is null.
</Property>
<Property name='limit' type='int' key='limit'>
(Optional) How many records to return in one request, default is the most recent 20 entries. Maximum 100, minimum 1.
</Property>
</Properties>
### Response
- `limit` (int) Number of items per page
- `has_more` (bool) Whether there is a next page
- `data` (array[object]) List of variables
- `id` (string) Variable ID
- `name` (string) Variable name
- `value_type` (string) Variable type (string, number, object, etc.)
- `value` (string) Variable value
- `description` (string) Variable description
- `created_at` (int) Creation timestamp
- `updated_at` (int) Last update timestamp
### Errors
- 404, `conversation_not_exists`, Conversation not found
</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/conversations/:conversation_id/variables" targetCode={`curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \\\n--header 'Authorization: Bearer {api_key}'`}>
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Request with variable name filter">
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123&variable_name=customer_name' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Response">
```json {{ title: 'Response' }}
{
"limit": 100,
"has_more": false,
"data": [
{
"id": "variable-uuid-1",
"name": "customer_name",
"value_type": "string",
"value": "John Doe",
"description": "Customer name extracted from the conversation",
"created_at": 1650000000000,
"updated_at": 1650000000000
},
{
"id": "variable-uuid-2",
"name": "order_details",
"value_type": "json",
"value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}",
"description": "Order details from the customer",
"created_at": 1650000000000,
"updated_at": 1650000000000
}
]
}
```
</CodeGroup>
</Col>
</Row>
---
<Heading <Heading
url='/audio-to-text' url='/audio-to-text'
method='POST' method='POST'

@ -912,6 +912,106 @@ import { Row, Col, Properties, Property, Heading, SubProperty, Paragraph } from
--- ---
<Heading
url='/conversations/:conversation_id/variables'
method='GET'
title='会話変数の取得'
name='#conversation-variables'
/>
<Row>
<Col>
特定の会話から変数を取得します。このエンドポイントは、会話中に取得された構造化データを抽出するのに役立ちます。
### パスパラメータ
<Properties>
<Property name='conversation_id' type='string' key='conversation_id'>
変数を取得する会話のID。
</Property>
</Properties>
### クエリパラメータ
<Properties>
<Property name='user' type='string' key='user'>
ユーザー識別子。開発者によって定義されたルールに従い、アプリケーション内で一意である必要があります。
</Property>
<Property name='last_id' type='string' key='last_id'>
(Optional)現在のページの最後の記録のID、デフォルトはnullです。
</Property>
<Property name='limit' type='int' key='limit'>
(Optional)1回のリクエストで返す記録の数、デフォルトは最新の20件です。最大100、最小1。
</Property>
</Properties>
### レスポンス
- `limit` (int) ページごとのアイテム数
- `has_more` (bool) さらにアイテムがあるかどうか
- `data` (array[object]) 変数のリスト
- `id` (string) 変数ID
- `name` (string) 変数名
- `value_type` (string) 変数タイプ(文字列、数値、真偽値など)
- `value` (string) 変数値
- `description` (string) 変数の説明
- `created_at` (int) 作成タイムスタンプ
- `updated_at` (int) 最終更新タイムスタンプ
### エラー
- 404, `conversation_not_exists`, 会話が見つかりません
</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/conversations/:conversation_id/variables" targetCode={`curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \\\n--header 'Authorization: Bearer {api_key}'`}>
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Request with variable name filter">
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123&variable_name=customer_name' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Response">
```json {{ title: 'Response' }}
{
"limit": 100,
"has_more": false,
"data": [
{
"id": "variable-uuid-1",
"name": "customer_name",
"value_type": "string",
"value": "John Doe",
"description": "会話から抽出された顧客名",
"created_at": 1650000000000,
"updated_at": 1650000000000
},
{
"id": "variable-uuid-2",
"name": "order_details",
"value_type": "json",
"value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}",
"description": "顧客の注文詳細",
"created_at": 1650000000000,
"updated_at": 1650000000000
}
]
}
```
</CodeGroup>
</Col>
</Row>
---
<Heading <Heading
url='/audio-to-text' url='/audio-to-text'
method='POST' method='POST'

@ -950,6 +950,106 @@ import { Row, Col, Properties, Property, Heading, SubProperty } from '../md.tsx'
--- ---
<Heading
url='/conversations/:conversation_id/variables'
method='GET'
title='获取对话变量'
name='#conversation-variables'
/>
<Row>
<Col>
从特定对话中检索变量。此端点对于提取对话过程中捕获的结构化数据非常有用。
### 路径参数
<Properties>
<Property name='conversation_id' type='string' key='conversation_id'>
要从中检索变量的对话ID。
</Property>
</Properties>
### 查询参数
<Properties>
<Property name='user' type='string' key='user'>
用户标识符,由开发人员定义的规则,在应用程序内必须唯一。
</Property>
<Property name='last_id' type='string' key='last_id'>
(选填)当前页最后面一条记录的 ID默认 null
</Property>
<Property name='limit' type='int' key='limit'>
(选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。
</Property>
</Properties>
### 响应
- `limit` (int) 每页项目数
- `has_more` (bool) 是否有更多项目
- `data` (array[object]) 变量列表
- `id` (string) 变量ID
- `name` (string) 变量名称
- `value_type` (string) 变量类型(字符串、数字、布尔等)
- `value` (string) 变量值
- `description` (string) 变量描述
- `created_at` (int) 创建时间戳
- `updated_at` (int) 最后更新时间戳
### 错误
- 404, `conversation_not_exists`, 对话不存在
</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/conversations/:conversation_id/variables" targetCode={`curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \\\n--header 'Authorization: Bearer {api_key}'`}>
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Request with variable name filter">
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123&variable_name=customer_name' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Response">
```json {{ title: 'Response' }}
{
"limit": 100,
"has_more": false,
"data": [
{
"id": "variable-uuid-1",
"name": "customer_name",
"value_type": "string",
"value": "John Doe",
"description": "客户名称(从对话中提取)",
"created_at": 1650000000000,
"updated_at": 1650000000000
},
{
"id": "variable-uuid-2",
"name": "order_details",
"value_type": "json",
"value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}",
"description": "客户的订单详情",
"created_at": 1650000000000,
"updated_at": 1650000000000
}
]
}
```
</CodeGroup>
</Col>
</Row>
---
<Heading <Heading
url='/audio-to-text' url='/audio-to-text'
method='POST' method='POST'

@ -949,6 +949,106 @@ Chat applications support session persistence, allowing previous chat history to
--- ---
<Heading
url='/conversations/:conversation_id/variables'
method='GET'
title='Get Conversation Variables'
name='#conversation-variables'
/>
<Row>
<Col>
Retrieve variables from a specific conversation. This endpoint is useful for extracting structured data that was captured during the conversation.
### Path Parameters
<Properties>
<Property name='conversation_id' type='string' key='conversation_id'>
The ID of the conversation to retrieve variables from.
</Property>
</Properties>
### Query Parameters
<Properties>
<Property name='user' type='string' key='user'>
The user identifier, defined by the developer, must ensure uniqueness within the application
</Property>
<Property name='last_id' type='string' key='last_id'>
(Optional) The ID of the last record on the current page, default is null.
</Property>
<Property name='limit' type='int' key='limit'>
(Optional) How many records to return in one request, default is the most recent 20 entries. Maximum 100, minimum 1.
</Property>
</Properties>
### Response
- `limit` (int) Number of items per page
- `has_more` (bool) Whether there is a next page
- `data` (array[object]) List of variables
- `id` (string) Variable ID
- `name` (string) Variable name
- `value_type` (string) Variable type (string, number, object, etc.)
- `value` (string) Variable value
- `description` (string) Variable description
- `created_at` (int) Creation timestamp
- `updated_at` (int) Last update timestamp
### Errors
- 404, `conversation_not_exists`, Conversation not found
</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/conversations/:conversation_id/variables" targetCode={`curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \\\n--header 'Authorization: Bearer {api_key}'`}>
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Request with variable name filter">
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123&variable_name=customer_name' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Response">
```json {{ title: 'Response' }}
{
"limit": 100,
"has_more": false,
"data": [
{
"id": "variable-uuid-1",
"name": "customer_name",
"value_type": "string",
"value": "John Doe",
"description": "Customer name extracted from the conversation",
"created_at": 1650000000000,
"updated_at": 1650000000000
},
{
"id": "variable-uuid-2",
"name": "order_details",
"value_type": "json",
"value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}",
"description": "Order details from the customer",
"created_at": 1650000000000,
"updated_at": 1650000000000
}
]
}
```
</CodeGroup>
</Col>
</Row>
---
<Heading <Heading
url='/audio-to-text' url='/audio-to-text'
method='POST' method='POST'

@ -945,6 +945,106 @@ import { Row, Col, Properties, Property, Heading, SubProperty, Paragraph } from
--- ---
<Heading
url='/conversations/:conversation_id/variables'
method='GET'
title='会話変数の取得'
name='#conversation-variables'
/>
<Row>
<Col>
特定の会話から変数を取得します。このエンドポイントは、会話中に取得された構造化データを抽出するのに役立ちます。
### パスパラメータ
<Properties>
<Property name='conversation_id' type='string' key='conversation_id'>
変数を取得する会話のID。
</Property>
</Properties>
### クエリパラメータ
<Properties>
<Property name='user' type='string' key='user'>
ユーザー識別子。開発者によって定義されたルールに従い、アプリケーション内で一意である必要があります。
</Property>
<Property name='last_id' type='string' key='last_id'>
(Optional)現在のページの最後のレコードのID、デフォルトはnullです。
</Property>
<Property name='limit' type='int' key='limit'>
(Optional)1回のリクエストで返すレコードの数、デフォルトは最新の20件です。最大100、最小1。
</Property>
</Properties>
### レスポンス
- `limit` (int) ページごとのアイテム数
- `has_more` (bool) さらにアイテムがあるかどうか
- `data` (array[object]) 変数のリスト
- `id` (string) 変数ID
- `name` (string) 変数名
- `value_type` (string) 変数タイプ(文字列、数値、真偽値など)
- `value` (string) 変数値
- `description` (string) 変数の説明
- `created_at` (int) 作成タイムスタンプ
- `updated_at` (int) 最終更新タイムスタンプ
### エラー
- 404, `conversation_not_exists`, 会話が見つかりません
</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/conversations/:conversation_id/variables" targetCode={`curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \\\n--header 'Authorization: Bearer {api_key}'`}>
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Request with variable name filter">
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123&variable_name=customer_name' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Response">
```json {{ title: 'Response' }}
{
"limit": 100,
"has_more": false,
"data": [
{
"id": "variable-uuid-1",
"name": "customer_name",
"value_type": "string",
"value": "John Doe",
"description": "会話から抽出された顧客名",
"created_at": 1650000000000,
"updated_at": 1650000000000
},
{
"id": "variable-uuid-2",
"name": "order_details",
"value_type": "json",
"value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}",
"description": "顧客の注文詳細",
"created_at": 1650000000000,
"updated_at": 1650000000000
}
]
}
```
</CodeGroup>
</Col>
</Row>
---
<Heading <Heading
url='/audio-to-text' url='/audio-to-text'
method='POST' method='POST'

@ -962,6 +962,106 @@ import { Row, Col, Properties, Property, Heading, SubProperty } from '../md.tsx'
--- ---
<Heading
url='/conversations/:conversation_id/variables'
method='GET'
title='获取对话变量'
name='#conversation-variables'
/>
<Row>
<Col>
从特定对话中检索变量。此端点对于提取对话过程中捕获的结构化数据非常有用。
### 路径参数
<Properties>
<Property name='conversation_id' type='string' key='conversation_id'>
要从中检索变量的对话ID。
</Property>
</Properties>
### 查询参数
<Properties>
<Property name='user' type='string' key='user'>
用户标识符,由开发人员定义的规则,在应用程序内必须唯一。
</Property>
<Property name='last_id' type='string' key='last_id'>
(选填)当前页最后面一条记录的 ID默认 null
</Property>
<Property name='limit' type='int' key='limit'>
(选填)一次请求返回多少条记录,默认 20 条,最大 100 条,最小 1 条。
</Property>
</Properties>
### 响应
- `limit` (int) 每页项目数
- `has_more` (bool) 是否有更多项目
- `data` (array[object]) 变量列表
- `id` (string) 变量ID
- `name` (string) 变量名称
- `value_type` (string) 变量类型(字符串、数字、布尔等)
- `value` (string) 变量值
- `description` (string) 变量描述
- `created_at` (int) 创建时间戳
- `updated_at` (int) 最后更新时间戳
### 错误
- 404, `conversation_not_exists`, 对话不存在
</Col>
<Col sticky>
<CodeGroup title="Request" tag="GET" label="/conversations/:conversation_id/variables" targetCode={`curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \\\n--header 'Authorization: Bearer {api_key}'`}>
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Request with variable name filter">
```bash {{ title: 'cURL' }}
curl -X GET '${props.appDetail.api_base_url}/conversations/{conversation_id}/variables?user=abc-123&variable_name=customer_name' \
--header 'Authorization: Bearer {api_key}'
```
</CodeGroup>
<CodeGroup title="Response">
```json {{ title: 'Response' }}
{
"limit": 100,
"has_more": false,
"data": [
{
"id": "variable-uuid-1",
"name": "customer_name",
"value_type": "string",
"value": "John Doe",
"description": "客户名称(从对话中提取)",
"created_at": 1650000000000,
"updated_at": 1650000000000
},
{
"id": "variable-uuid-2",
"name": "order_details",
"value_type": "json",
"value": "{\"product\":\"Widget\",\"quantity\":5,\"price\":19.99}",
"description": "客户的订单详情",
"created_at": 1650000000000,
"updated_at": 1650000000000
}
]
}
```
</CodeGroup>
</Col>
</Row>
---
<Heading <Heading
url='/audio-to-text' url='/audio-to-text'
method='POST' method='POST'

@ -3,7 +3,6 @@ import type {
Model, Model,
ModelProvider, ModelProvider,
} from '../declarations' } from '../declarations'
import { basePath } from '@/utils/var'
import { useLanguage } from '../hooks' import { useLanguage } from '../hooks'
import { Group } from '@/app/components/base/icons/src/vender/other' import { Group } from '@/app/components/base/icons/src/vender/other'
import { OpenaiBlue, OpenaiViolet } from '@/app/components/base/icons/src/public/llm' import { OpenaiBlue, OpenaiViolet } from '@/app/components/base/icons/src/public/llm'
@ -31,7 +30,7 @@ const ModelIcon: FC<ModelIconProps> = ({
if (provider?.icon_small) { if (provider?.icon_small) {
return ( return (
<div className={cn('flex h-5 w-5 items-center justify-center', isDeprecated && 'opacity-50', className)}> <div className={cn('flex h-5 w-5 items-center justify-center', isDeprecated && 'opacity-50', className)}>
<img alt='model-icon' src={basePath + renderI18nObject(provider.icon_small, language)}/> <img alt='model-icon' src={renderI18nObject(provider.icon_small, language)}/>
</div> </div>
) )
} }

@ -14,6 +14,7 @@ import Nav from '../nav'
import type { NavItem } from '../nav/nav-selector' import type { NavItem } from '../nav/nav-selector'
import { fetchDatasetDetail, fetchDatasets } from '@/service/datasets' import { fetchDatasetDetail, fetchDatasets } from '@/service/datasets'
import type { DataSetListResponse } from '@/models/datasets' import type { DataSetListResponse } from '@/models/datasets'
import { basePath } from '@/utils/var'
const getKey = (pageIndex: number, previousPageData: DataSetListResponse) => { const getKey = (pageIndex: number, previousPageData: DataSetListResponse) => {
if (!pageIndex || previousPageData.has_more) if (!pageIndex || previousPageData.has_more)
@ -56,7 +57,7 @@ const DatasetNav = () => {
icon_background: dataset.icon_background, icon_background: dataset.icon_background,
})) as NavItem[]} })) as NavItem[]}
createText={t('common.menus.newDataset')} createText={t('common.menus.newDataset')}
onCreate={() => router.push('/datasets/create')} onCreate={() => router.push(`${basePath}/datasets/create`)}
onLoadmore={handleLoadmore} onLoadmore={handleLoadmore}
/> />
) )

@ -3,9 +3,15 @@ import ChatVariableButton from '@/app/components/workflow/header/chat-variable-b
import { import {
useNodesReadOnly, useNodesReadOnly,
} from '@/app/components/workflow/hooks' } from '@/app/components/workflow/hooks'
import { useIsChatMode } from '../../hooks'
const ChatVariableTrigger = () => { const ChatVariableTrigger = () => {
const { nodesReadOnly } = useNodesReadOnly() const { nodesReadOnly } = useNodesReadOnly()
const isChatMode = useIsChatMode()
if (!isChatMode)
return null
return <ChatVariableButton disabled={nodesReadOnly} /> return <ChatVariableButton disabled={nodesReadOnly} />
} }
export default memo(ChatVariableTrigger) export default memo(ChatVariableTrigger)

@ -74,7 +74,7 @@ const WorkflowPanelOnRight = () => {
) )
} }
{ {
showChatVariablePanel && ( showChatVariablePanel && isChatMode && (
<ChatVariablePanel /> <ChatVariablePanel />
) )
} }

@ -16,6 +16,7 @@ import Button from '@/app/components/base/button'
import { fetchInitValidateStatus, fetchSetupStatus, setup } from '@/service/common' import { fetchInitValidateStatus, fetchSetupStatus, setup } from '@/service/common'
import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common' import type { InitValidateStatusResponse, SetupStatusResponse } from '@/models/common'
import { basePath } from '@/utils/var'
const validPassword = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/ const validPassword = /^(?=.*[a-zA-Z])(?=.*\d).{8,}$/
@ -80,12 +81,12 @@ const InstallForm = () => {
fetchSetupStatus().then((res: SetupStatusResponse) => { fetchSetupStatus().then((res: SetupStatusResponse) => {
if (res.step === 'finished') { if (res.step === 'finished') {
localStorage.setItem('setup_status', 'finished') localStorage.setItem('setup_status', 'finished')
router.push('/signin') router.push(`${basePath}/signin`)
} }
else { else {
fetchInitValidateStatus().then((res: InitValidateStatusResponse) => { fetchInitValidateStatus().then((res: InitValidateStatusResponse) => {
if (res.status === 'not_started') if (res.status === 'not_started')
router.push('/init') router.push(`${basePath}/init`)
}) })
} }
setLoading(false) setLoading(false)

@ -17,6 +17,7 @@ import {
} from '@/app/components/header/account-setting/model-provider-page/declarations' } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Model, ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations' import type { Model, ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { RETRIEVE_METHOD } from '@/types/app' import type { RETRIEVE_METHOD } from '@/types/app'
import type { BasicPlan } from '@/app/components/billing/type'
import { Plan, type UsagePlanInfo } from '@/app/components/billing/type' import { Plan, type UsagePlanInfo } from '@/app/components/billing/type'
import { fetchCurrentPlanInfo } from '@/service/billing' import { fetchCurrentPlanInfo } from '@/service/billing'
import { parseCurrentPlan } from '@/app/components/billing/utils' import { parseCurrentPlan } from '@/app/components/billing/utils'
@ -34,7 +35,7 @@ type ProviderContextState = {
supportRetrievalMethods: RETRIEVE_METHOD[] supportRetrievalMethods: RETRIEVE_METHOD[]
isAPIKeySet: boolean isAPIKeySet: boolean
plan: { plan: {
type: Plan type: BasicPlan
usage: UsagePlanInfo usage: UsagePlanInfo
total: UsagePlanInfo total: UsagePlanInfo
} }

@ -55,6 +55,10 @@ const translation = {
vectorSpaceTooltip: 'Documents with the High Quality indexing mode will consume Knowledge Data Storage resources. When Knowledge Data Storage reaches the limit, new documents will not be uploaded.', vectorSpaceTooltip: 'Documents with the High Quality indexing mode will consume Knowledge Data Storage resources. When Knowledge Data Storage reaches the limit, new documents will not be uploaded.',
documentsRequestQuota: '{{count,number}}/min Knowledge Request Rate Limit', documentsRequestQuota: '{{count,number}}/min Knowledge Request Rate Limit',
documentsRequestQuotaTooltip: 'Specifies the total number of actions a workspace can perform per minute within the knowledge base, including dataset creation, deletion, updates, document uploads, modifications, archiving, and knowledge base queries. This metric is used to evaluate the performance of knowledge base requests. For example, if a Sandbox user performs 10 consecutive hit tests within one minute, their workspace will be temporarily restricted from performing the following actions for the next minute: dataset creation, deletion, updates, and document uploads or modifications. ', documentsRequestQuotaTooltip: 'Specifies the total number of actions a workspace can perform per minute within the knowledge base, including dataset creation, deletion, updates, document uploads, modifications, archiving, and knowledge base queries. This metric is used to evaluate the performance of knowledge base requests. For example, if a Sandbox user performs 10 consecutive hit tests within one minute, their workspace will be temporarily restricted from performing the following actions for the next minute: dataset creation, deletion, updates, and document uploads or modifications. ',
apiRateLimit: 'API Rate Limit',
apiRateLimitUnit: '{{count,number}}/day',
unlimitedApiRate: 'No API Rate Limit',
apiRateLimitTooltip: 'API Rate Limit applies to all requests made through the Dify API, including text generation, chat conversations, workflow executions, and document processing.',
documentProcessingPriority: ' Document Processing', documentProcessingPriority: ' Document Processing',
documentProcessingPriorityUpgrade: 'Process more data with higher accuracy at faster speeds.', documentProcessingPriorityUpgrade: 'Process more data with higher accuracy at faster speeds.',
priority: { priority: {

@ -54,6 +54,10 @@ const translation = {
vectorSpaceTooltip: '高品質インデックスモードのドキュメントは、知識データストレージのリソースを消費します。知識データストレージの上限に達すると、新しいドキュメントはアップロードされません。', vectorSpaceTooltip: '高品質インデックスモードのドキュメントは、知識データストレージのリソースを消費します。知識データストレージの上限に達すると、新しいドキュメントはアップロードされません。',
documentsRequestQuota: '{{count,number}}/分のナレッジ リクエストのレート制限', documentsRequestQuota: '{{count,number}}/分のナレッジ リクエストのレート制限',
documentsRequestQuotaTooltip: 'ナレッジベース内でワークスペースが1分間に実行できる操作の総数を示します。これには、データセットの作成、削除、更新、ドキュメントのアップロード、修正、アーカイブ、およびナレッジベースクエリが含まれます。この指標は、ナレッジベースリクエストのパフォーマンスを評価するために使用されます。例えば、Sandbox ユーザーが1分間に10回連続でヒットテストを実行した場合、そのワークスペースは次の1分間、データセットの作成、削除、更新、ドキュメントのアップロードや修正などの操作を一時的に実行できなくなります。', documentsRequestQuotaTooltip: 'ナレッジベース内でワークスペースが1分間に実行できる操作の総数を示します。これには、データセットの作成、削除、更新、ドキュメントのアップロード、修正、アーカイブ、およびナレッジベースクエリが含まれます。この指標は、ナレッジベースリクエストのパフォーマンスを評価するために使用されます。例えば、Sandbox ユーザーが1分間に10回連続でヒットテストを実行した場合、そのワークスペースは次の1分間、データセットの作成、削除、更新、ドキュメントのアップロードや修正などの操作を一時的に実行できなくなります。',
apiRateLimit: 'APIレート制限',
apiRateLimitUnit: '{{count,number}}/日',
unlimitedApiRate: '無制限のAPIコール',
apiRateLimitTooltip: 'APIレート制限は、テキスト生成、チャットボット、ワークフロー、ドキュメント処理など、Dify API経由のすべてのリクエストに適用されます。',
documentProcessingPriority: '文書処理', documentProcessingPriority: '文書処理',
documentProcessingPriorityUpgrade: 'より高い精度と高速な速度でデータを処理します。', documentProcessingPriorityUpgrade: 'より高い精度と高速な速度でデータを処理します。',
priority: { priority: {
@ -100,17 +104,17 @@ const translation = {
}, },
plans: { plans: {
sandbox: { sandbox: {
name: 'Sandbox(サンドボックス)', name: 'Sandbox',
for: '主要機能の無料体験', for: '主要機能の無料体験',
description: '主要機能を無料で体験', description: '主要機能を無料で体験',
}, },
professional: { professional: {
name: 'Professional(プロフェッショナル)', name: 'Professional',
for: '個人開発者/小規模チーム向け', for: '個人開発者/小規模チーム向け',
description: '個人開発者・小規模チームに最適', description: '個人開発者・小規模チームに最適',
}, },
team: { team: {
name: 'Team(チーム)', name: 'Team',
for: '中規模チーム向け', for: '中規模チーム向け',
description: '成長期のチームに必要な機能を備えたプラン', description: '成長期のチームに必要な機能を備えたプラン',
}, },

@ -54,6 +54,10 @@ const translation = {
vectorSpaceTooltip: '采用高质量索引模式的文档会消耗知识数据存储资源。当知识数据存储达到限制时,将不会上传新文档。', vectorSpaceTooltip: '采用高质量索引模式的文档会消耗知识数据存储资源。当知识数据存储达到限制时,将不会上传新文档。',
documentsRequestQuota: '{{count,number}}/分钟 知识库请求频率限制', documentsRequestQuota: '{{count,number}}/分钟 知识库请求频率限制',
documentsRequestQuotaTooltip: '指每分钟内一个空间在知识库中可执行的操作总数包括数据集的创建、删除、更新文档的上传、修改、归档以及知识库查询等用于评估知识库请求的性能。例如Sandbox 用户在 1 分钟内连续执行 10 次命中测试,其工作区将在接下来的 1 分钟内无法继续执行以下操作:数据集的创建、删除、更新,文档的上传、修改等操作。', documentsRequestQuotaTooltip: '指每分钟内一个空间在知识库中可执行的操作总数包括数据集的创建、删除、更新文档的上传、修改、归档以及知识库查询等用于评估知识库请求的性能。例如Sandbox 用户在 1 分钟内连续执行 10 次命中测试,其工作区将在接下来的 1 分钟内无法继续执行以下操作:数据集的创建、删除、更新,文档的上传、修改等操作。',
apiRateLimit: 'API 请求频率限制',
apiRateLimitUnit: '{{count,number}} 次/天',
unlimitedApiRate: 'API 请求频率无限制',
apiRateLimitTooltip: 'API 请求频率限制涵盖所有通过 Dify API 发起的调用,例如文本生成、聊天对话、工作流执行和文档处理等。',
documentProcessingPriority: '文档处理', documentProcessingPriority: '文档处理',
documentProcessingPriorityUpgrade: '以更快的速度、更高的精度处理更多的数据。', documentProcessingPriorityUpgrade: '以更快的速度、更高的精度处理更多的数据。',
priority: { priority: {

@ -1,4 +1,4 @@
const { basePath } = require('./utils/var-basePath') const { basePath, assetPrefix } = require('./utils/var-basePath')
const { codeInspectorPlugin } = require('code-inspector-plugin') const { codeInspectorPlugin } = require('code-inspector-plugin')
const withMDX = require('@next/mdx')({ const withMDX = require('@next/mdx')({
extension: /\.mdx?$/, extension: /\.mdx?$/,
@ -16,6 +16,7 @@ const withMDX = require('@next/mdx')({
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
basePath, basePath,
assetPrefix,
webpack: (config, { dev, isServer }) => { webpack: (config, { dev, isServer }) => {
config.plugins.push(codeInspectorPlugin({ bundler: 'webpack' })) config.plugins.push(codeInspectorPlugin({ bundler: 'webpack' }))
return config return config

@ -2,4 +2,5 @@
// same as the one exported from var.ts // same as the one exported from var.ts
module.exports = { module.exports = {
basePath: '', basePath: '',
assetPrefix: '',
} }

Loading…
Cancel
Save