Compare commits

..

1 Commits

Author SHA1 Message Date
Fred
27ac18d9d7 feat: init support for deepseek 2024-05-15 14:47:43 +08:00
145 changed files with 3393 additions and 17689 deletions

View File

@@ -1,20 +1,21 @@
# Your openai api key. (required)
OPENAI_API_KEY=sk-xxxx
# Access password, separated by comma. (optional)
CODE=your-password
# You can start service behind a proxy. (optional)
# You can start service behind a proxy
PROXY_URL=http://localhost:7890
# (optional)
# Default: Empty
# Google Gemini Pro API key, set if you want to use Google Gemini Pro API.
# Googel Gemini Pro API key, set if you want to use Google Gemini Pro API.
GOOGLE_API_KEY=
# (optional)
# Default: https://generativelanguage.googleapis.com/
# Google Gemini Pro API url without pathname, set if you want to customize Google Gemini Pro API url.
# Googel Gemini Pro API url without pathname, set if you want to customize Google Gemini Pro API url.
GOOGLE_URL=
# Override openai api request base url. (optional)
@@ -46,15 +47,6 @@ ENABLE_BALANCE_QUERY=
# If you want to disable parse settings from url, set this value to 1.
DISABLE_FAST_LINK=
# (optional)
# Default: Empty
# To control custom models, use + to add a custom model, use - to hide a model, use name=displayName to customize model name, separated by comma.
CUSTOM_MODELS=
# (optional)
# Default: Empty
# Change default model
DEFAULT_MODEL=
# anthropic claude Api Key.(optional)
ANTHROPIC_API_KEY=
@@ -62,8 +54,11 @@ ANTHROPIC_API_KEY=
### anthropic claude Api version. (optional)
ANTHROPIC_API_VERSION=
# deepseek api key (optional)
DEEPSEEK_API_KEY=
### anthropic claude Api url (optional)
ANTHROPIC_URL=
### (optional)
WHITE_WEBDEV_ENDPOINTS=
WEBDEV_ENDPOINTS_WHITELIST=

View File

@@ -1,80 +0,0 @@
name: '🐛 Bug Report'
description: 'Report an bug'
title: '[Bug] '
labels: ['bug']
body:
- type: dropdown
attributes:
label: '📦 Deployment Method'
multiple: true
options:
- 'Official installation package'
- 'Vercel'
- 'Zeabur'
- 'Sealos'
- 'Netlify'
- 'Docker'
- 'Other'
validations:
required: true
- type: input
attributes:
label: '📌 Version'
validations:
required: true
- type: dropdown
attributes:
label: '💻 Operating System'
multiple: true
options:
- 'Windows'
- 'macOS'
- 'Ubuntu'
- 'Other Linux'
- 'iOS'
- 'iPad OS'
- 'Android'
- 'Other'
validations:
required: true
- type: input
attributes:
label: '📌 System Version'
validations:
required: true
- type: dropdown
attributes:
label: '🌐 Browser'
multiple: true
options:
- 'Chrome'
- 'Edge'
- 'Safari'
- 'Firefox'
- 'Other'
validations:
required: true
- type: input
attributes:
label: '📌 Browser Version'
validations:
required: true
- type: textarea
attributes:
label: '🐛 Bug Description'
description: A clear and concise description of the bug, if the above option is `Other`, please also explain in detail.
validations:
required: true
- type: textarea
attributes:
label: '📷 Recurrence Steps'
description: A clear and concise description of how to recurrence.
- type: textarea
attributes:
label: '🚦 Expected Behavior'
description: A clear and concise description of what you expected to happen.
- type: textarea
attributes:
label: '📝 Additional Information'
description: If your problem needs further explanation, or if the issue you're seeing cannot be reproduced in a gist, please add more information here.

View File

@@ -1,80 +0,0 @@
name: '🐛 反馈缺陷'
description: '反馈一个问题/缺陷'
title: '[Bug] '
labels: ['bug']
body:
- type: dropdown
attributes:
label: '📦 部署方式'
multiple: true
options:
- '官方安装包'
- 'Vercel'
- 'Zeabur'
- 'Sealos'
- 'Netlify'
- 'Docker'
- 'Other'
validations:
required: true
- type: input
attributes:
label: '📌 软件版本'
validations:
required: true
- type: dropdown
attributes:
label: '💻 系统环境'
multiple: true
options:
- 'Windows'
- 'macOS'
- 'Ubuntu'
- 'Other Linux'
- 'iOS'
- 'iPad OS'
- 'Android'
- 'Other'
validations:
required: true
- type: input
attributes:
label: '📌 系统版本'
validations:
required: true
- type: dropdown
attributes:
label: '🌐 浏览器'
multiple: true
options:
- 'Chrome'
- 'Edge'
- 'Safari'
- 'Firefox'
- 'Other'
validations:
required: true
- type: input
attributes:
label: '📌 浏览器版本'
validations:
required: true
- type: textarea
attributes:
label: '🐛 问题描述'
description: 请提供一个清晰且简洁的问题描述,若上述选项为`Other`,也请详细说明。
validations:
required: true
- type: textarea
attributes:
label: '📷 复现步骤'
description: 请提供一个清晰且简洁的描述,说明如何复现问题。
- type: textarea
attributes:
label: '🚦 期望结果'
description: 请提供一个清晰且简洁的描述,说明您期望发生什么。
- type: textarea
attributes:
label: '📝 补充信息'
description: 如果您的问题需要进一步说明,或者您遇到的问题无法在一个简单的示例中复现,请在这里添加更多信息。

View File

@@ -1,21 +0,0 @@
name: '🌠 Feature Request'
description: 'Suggest an idea'
title: '[Feature Request] '
labels: ['enhancement']
body:
- type: textarea
attributes:
label: '🥰 Feature Description'
description: Please add a clear and concise description of the problem you are seeking to solve with this feature request.
validations:
required: true
- type: textarea
attributes:
label: '🧐 Proposed Solution'
description: Describe the solution you'd like in a clear and concise manner.
validations:
required: true
- type: textarea
attributes:
label: '📝 Additional Information'
description: Add any other context about the problem here.

View File

@@ -1,21 +0,0 @@
name: '🌠 功能需求'
description: '提出需求或建议'
title: '[Feature Request] '
labels: ['enhancement']
body:
- type: textarea
attributes:
label: '🥰 需求描述'
description: 请添加一个清晰且简洁的问题描述,阐述您希望通过这个功能需求解决的问题。
validations:
required: true
- type: textarea
attributes:
label: '🧐 解决方案'
description: 请清晰且简洁地描述您想要的解决方案。
validations:
required: true
- type: textarea
attributes:
label: '📝 补充信息'
description: 在这里添加关于问题的任何其他背景信息。

146
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@@ -0,0 +1,146 @@
name: Bug report
description: Create a report to help us improve
title: "[Bug] "
labels: ["bug"]
body:
- type: markdown
attributes:
value: "## Describe the bug"
- type: textarea
id: bug-description
attributes:
label: "Bug Description"
description: "A clear and concise description of what the bug is."
placeholder: "Explain the bug..."
validations:
required: true
- type: markdown
attributes:
value: "## To Reproduce"
- type: textarea
id: steps-to-reproduce
attributes:
label: "Steps to Reproduce"
description: "Steps to reproduce the behavior:"
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: markdown
attributes:
value: "## Expected behavior"
- type: textarea
id: expected-behavior
attributes:
label: "Expected Behavior"
description: "A clear and concise description of what you expected to happen."
placeholder: "Describe what you expected to happen..."
validations:
required: true
- type: markdown
attributes:
value: "## Screenshots"
- type: textarea
id: screenshots
attributes:
label: "Screenshots"
description: "If applicable, add screenshots to help explain your problem."
placeholder: "Paste your screenshots here or write 'N/A' if not applicable..."
validations:
required: false
- type: markdown
attributes:
value: "## Deployment"
- type: checkboxes
id: deployment
attributes:
label: "Deployment Method"
description: "Please select the deployment method you are using."
options:
- label: "Docker"
- label: "Vercel"
- label: "Server"
- type: markdown
attributes:
value: "## Desktop (please complete the following information):"
- type: input
id: desktop-os
attributes:
label: "Desktop OS"
description: "Your desktop operating system."
placeholder: "e.g., Windows 10"
validations:
required: false
- type: input
id: desktop-browser
attributes:
label: "Desktop Browser"
description: "Your desktop browser."
placeholder: "e.g., Chrome, Safari"
validations:
required: false
- type: input
id: desktop-version
attributes:
label: "Desktop Browser Version"
description: "Version of your desktop browser."
placeholder: "e.g., 89.0"
validations:
required: false
- type: markdown
attributes:
value: "## Smartphone (please complete the following information):"
- type: input
id: smartphone-device
attributes:
label: "Smartphone Device"
description: "Your smartphone device."
placeholder: "e.g., iPhone X"
validations:
required: false
- type: input
id: smartphone-os
attributes:
label: "Smartphone OS"
description: "Your smartphone operating system."
placeholder: "e.g., iOS 14.4"
validations:
required: false
- type: input
id: smartphone-browser
attributes:
label: "Smartphone Browser"
description: "Your smartphone browser."
placeholder: "e.g., Safari"
validations:
required: false
- type: input
id: smartphone-version
attributes:
label: "Smartphone Browser Version"
description: "Version of your smartphone browser."
placeholder: "e.g., 14"
validations:
required: false
- type: markdown
attributes:
value: "## Additional Logs"
- type: textarea
id: additional-logs
attributes:
label: "Additional Logs"
description: "Add any logs about the problem here."
placeholder: "Paste any relevant logs here..."
validations:
required: false

View File

@@ -0,0 +1,53 @@
name: Feature request
description: Suggest an idea for this project
title: "[Feature Request]: "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: "## Is your feature request related to a problem? Please describe."
- type: textarea
id: problem-description
attributes:
label: Problem Description
description: "A clear and concise description of what the problem is. Example: I'm always frustrated when [...]"
placeholder: "Explain the problem you are facing..."
validations:
required: true
- type: markdown
attributes:
value: "## Describe the solution you'd like"
- type: textarea
id: desired-solution
attributes:
label: Solution Description
description: A clear and concise description of what you want to happen.
placeholder: "Describe the solution you'd like..."
validations:
required: true
- type: markdown
attributes:
value: "## Describe alternatives you've considered"
- type: textarea
id: alternatives-considered
attributes:
label: Alternatives Considered
description: A clear and concise description of any alternative solutions or features you've considered.
placeholder: "Describe any alternative solutions or features you've considered..."
validations:
required: false
- type: markdown
attributes:
value: "## Additional context"
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: Add any other context or screenshots about the feature request here.
placeholder: "Add any other context or screenshots about the feature request here..."
validations:
required: false

View File

@@ -1,28 +0,0 @@
#### 💻 变更类型 | Change Type
<!-- For change type, change [ ] to [x]. -->
- [ ] feat <!-- 引入新功能 | Introduce new features -->
- [ ] fix <!-- 修复 Bug | Fix a bug -->
- [ ] refactor <!-- 重构代码(既不修复 Bug 也不添加新功能) | Refactor code that neither fixes a bug nor adds a feature -->
- [ ] perf <!-- 提升性能的代码变更 | A code change that improves performance -->
- [ ] style <!-- 添加或更新不影响代码含义的样式文件 | Add or update style files that do not affect the meaning of the code -->
- [ ] test <!-- 添加缺失的测试或纠正现有的测试 | Adding missing tests or correcting existing tests -->
- [ ] docs <!-- 仅文档更新 | Documentation only changes -->
- [ ] ci <!-- 修改持续集成配置文件和脚本 | Changes to our CI configuration files and scripts -->
- [ ] chore <!-- 其他不修改 src 或 test 文件的变更 | Other changes that dont modify src or test files -->
- [ ] build <!-- 进行架构变更 | Make architectural changes -->
#### 🔀 变更说明 | Description of Change
<!--
感谢您的 Pull Request ,请提供此 Pull Request 的变更说明
Thank you for your Pull Request. Please provide a description above.
-->
#### 📝 补充信息 | Additional Information
<!--
请添加与此 Pull Request 相关的补充信息
Add any other context about the Pull Request here.
-->

4
.gitignore vendored
View File

@@ -43,6 +43,4 @@ dev
.env
*.key
*.key.pub
masks.json
*.key.pub

View File

@@ -43,7 +43,7 @@ COPY --from=builder /app/.next/server ./.next/server
EXPOSE 3000
CMD if [ -n "$PROXY_URL" ]; then \
export HOSTNAME="0.0.0.0"; \
export HOSTNAME="127.0.0.1"; \
protocol=$(echo $PROXY_URL | cut -d: -f1); \
host=$(echo $PROXY_URL | cut -d/ -f3 | cut -d: -f1); \
port=$(echo $PROXY_URL | cut -d: -f3); \

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023-2024 Zhang Yifei
Copyright (c) 2023 Zhang Yifei
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

146
README.md
View File

@@ -1,8 +1,5 @@
<div align="center">
<a href='#企业版'>
<img src="./docs/images/ent.svg" alt="icon"/>
</a>
<img src="./docs/images/head-cover.png" alt="icon"/>
<h1 align="center">NextChat (ChatGPT Next Web)</h1>
@@ -17,51 +14,27 @@ One-Click to get a well-designed cross-platform ChatGPT web UI, with GPT3, GPT4
[![MacOS][MacOS-image]][download-url]
[![Linux][Linux-image]][download-url]
[Web App](https://app.nextchat.dev/) / [Desktop App](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [Discord](https://discord.gg/YCkeafCafC) / [Enterprise Edition](#enterprise-edition) / [Twitter](https://twitter.com/NextChatDev)
[Web App](https://app.nextchat.dev/) / [Desktop App](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [Discord](https://discord.gg/YCkeafCafC) / [Twitter](https://twitter.com/NextChatDev)
[网页版](https://app.nextchat.dev/) / [客户端](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [企业版](#%E4%BC%81%E4%B8%9A%E7%89%88) / [反馈](https://github.com/Yidadaa/ChatGPT-Next-Web/issues)
[网页版](https://app.nextchat.dev/) / [客户端](https://github.com/Yidadaa/ChatGPT-Next-Web/releases) / [反馈](https://github.com/Yidadaa/ChatGPT-Next-Web/issues)
[web-url]: https://app.nextchat.dev/
[web-url]: https://chatgpt.nextweb.fun
[download-url]: https://github.com/Yidadaa/ChatGPT-Next-Web/releases
[Web-image]: https://img.shields.io/badge/Web-PWA-orange?logo=microsoftedge
[Windows-image]: https://img.shields.io/badge/-Windows-blue?logo=windows
[MacOS-image]: https://img.shields.io/badge/-MacOS-black?logo=apple
[Linux-image]: https://img.shields.io/badge/-Linux-333?logo=ubuntu
[<img src="https://vercel.com/button" alt="Deploy on Zeabur" height="30">](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat) [<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="30">](https://zeabur.com/templates/ZBUEFA) [<img src="https://gitpod.io/button/open-in-gitpod.svg" alt="Open in Gitpod" height="30">](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat)
[<img src="https://github.com/user-attachments/assets/903482d4-3e87-4134-9af1-f2588fa90659" height="60" width="288" >](https://monica.im/?utm=nxcrp)
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/ZBUEFA)
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
![cover](./docs/images/cover.png)
</div>
## Enterprise Edition
Meeting Your Company's Privatization and Customization Deployment Requirements:
- **Brand Customization**: Tailored VI/UI to seamlessly align with your corporate brand image.
- **Resource Integration**: Unified configuration and management of dozens of AI resources by company administrators, ready for use by team members.
- **Permission Control**: Clearly defined member permissions, resource permissions, and knowledge base permissions, all controlled via a corporate-grade Admin Panel.
- **Knowledge Integration**: Combining your internal knowledge base with AI capabilities, making it more relevant to your company's specific business needs compared to general AI.
- **Security Auditing**: Automatically intercept sensitive inquiries and trace all historical conversation records, ensuring AI adherence to corporate information security standards.
- **Private Deployment**: Enterprise-level private deployment supporting various mainstream private cloud solutions, ensuring data security and privacy protection.
- **Continuous Updates**: Ongoing updates and upgrades in cutting-edge capabilities like multimodal AI, ensuring consistent innovation and advancement.
For enterprise inquiries, please contact: **business@nextchat.dev**
## 企业版
满足企业用户私有化部署和个性化定制需求:
- **品牌定制**:企业量身定制 VI/UI与企业品牌形象无缝契合
- **资源集成**:由企业管理人员统一配置和管理数十种 AI 资源,团队成员开箱即用
- **权限管理**:成员权限、资源权限、知识库权限层级分明,企业级 Admin Panel 统一控制
- **知识接入**:企业内部知识库与 AI 能力相结合,比通用 AI 更贴近企业自身业务需求
- **安全审计**:自动拦截敏感提问,支持追溯全部历史对话记录,让 AI 也能遵循企业信息安全规范
- **私有部署**:企业级私有部署,支持各类主流私有云部署,确保数据安全和隐私保护
- **持续更新**:提供多模态、智能体等前沿能力持续更新升级服务,常用常新、持续先进
企业版咨询: **business@nextchat.dev**
<img width="300" src="https://github.com/user-attachments/assets/3daeb7b6-ab63-4542-9141-2e4a12c80601">
## Features
- **Deploy for free with one-click** on Vercel in under 1 minute
@@ -76,12 +49,6 @@ For enterprise inquiries, please contact: **business@nextchat.dev**
- Automatically compresses chat history to support long conversations while also saving your tokens
- I18n: English, 简体中文, 繁体中文, 日本語, Français, Español, Italiano, Türkçe, Deutsch, Tiếng Việt, Русский, Čeština, 한국어, Indonesia
<div align="center">
![主界面](./docs/images/cover.png)
</div>
## Roadmap
- [x] System Prompt: pin a user defined prompt as system prompt [#138](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/138)
@@ -90,15 +57,10 @@ For enterprise inquiries, please contact: **business@nextchat.dev**
- [x] Share as image, share to ShareGPT [#1741](https://github.com/Yidadaa/ChatGPT-Next-Web/pull/1741)
- [x] Desktop App with tauri
- [x] Self-host Model: Fully compatible with [RWKV-Runner](https://github.com/josStorer/RWKV-Runner), as well as server deployment of [LocalAI](https://github.com/go-skynet/LocalAI): llama/gpt4all/rwkv/vicuna/koala/gpt4all-j/cerebras/falcon/dolly etc.
- [x] Artifacts: Easily preview, copy and share generated content/webpages through a separate window [#5092](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/pull/5092)
- [x] Plugins: support network search, calculator, any other apis etc. [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) [#5353](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5353)
- [x] network search, calculator, any other apis etc. [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) [#5353](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5353)
- [ ] local knowledge base
- [ ] Plugins: support network search, calculator, any other apis etc. [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165)
## What's New
- 🚀 v2.15.0 Now supports Plugins! Read this: [NextChat-Awesome-Plugins](https://github.com/ChatGPTNextWeb/NextChat-Awesome-Plugins)
- 🚀 v2.14.0 Now supports Artifacts & SD
- 🚀 v2.10.1 support Google Gemini Pro model.
- 🚀 v2.9.11 you can use azure endpoint now.
- 🚀 v2.8 now we have a client that runs across all platforms!
@@ -127,21 +89,15 @@ For enterprise inquiries, please contact: **business@nextchat.dev**
- [x] 分享为图片,分享到 ShareGPT 链接 [#1741](https://github.com/Yidadaa/ChatGPT-Next-Web/pull/1741)
- [x] 使用 tauri 打包桌面应用
- [x] 支持自部署的大语言模型:开箱即用 [RWKV-Runner](https://github.com/josStorer/RWKV-Runner) ,服务端部署 [LocalAI 项目](https://github.com/go-skynet/LocalAI) llama / gpt4all / rwkv / vicuna / koala / gpt4all-j / cerebras / falcon / dolly 等等,或者使用 [api-for-open-llm](https://github.com/xusenlinzy/api-for-open-llm)
- [x] Artifacts: 通过独立窗口,轻松预览、复制和分享生成的内容/可交互网页 [#5092](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/pull/5092)
- [x] 插件机制,支持`联网搜索``计算器`、调用其他平台 api [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) [#5353](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5353)
- [x] 支持联网搜索、计算器、调用其他平台 api [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165) [#5353](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5353)
- [ ] 本地知识库
- [ ] 插件机制,支持联网搜索、计算器、调用其他平台 api [#165](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/165)
## 最新动态
- 🚀 v2.15.0 现在支持插件功能了!了解更多:[NextChat-Awesome-Plugins](https://github.com/ChatGPTNextWeb/NextChat-Awesome-Plugins)
- 🚀 v2.14.0 现在支持 Artifacts & SD 了。
- 🚀 v2.10.1 现在支持 Gemini Pro 模型。
- 🚀 v2.9.11 现在可以使用自定义 Azure 服务了。
- 🚀 v2.8 发布了横跨 Linux/Windows/MacOS 的体积极小的客户端。
- 🚀 v2.7 现在可以将会话分享为图片了,也可以分享到 ShareGPT 的在线链接。
- 🚀 v2.0 已经发布,现在你可以使用面具功能快速创建预制对话了! 了解更多: [ChatGPT 提示词高阶技能:零次、一次和少样本提示](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/138)。
- 💡 想要更方便地随时随地使用本项目可以试下这款桌面插件https://github.com/mushan0x0/AI0x0.com
- 🚀 v2.7 现在可以将会话分享为图片了,也可以分享到 ShareGPT 的在线链接。
- 🚀 v2.8 发布了横跨 Linux/Windows/MacOS 的体积极小的客户端。
- 🚀 v2.9.11 现在可以使用自定义 Azure 服务了。
## Get Started
@@ -224,7 +180,7 @@ Specify OpenAI organization ID.
### `AZURE_URL` (optional)
> Example: https://{azure-resource-url}/openai
> Example: https://{azure-resource-url}/openai/deployments/{deploy-name}
Azure deploy url.
@@ -256,45 +212,9 @@ anthropic claude Api version.
anthropic claude Api Url.
### `BAIDU_API_KEY` (optional)
### `DEEPSEEK_API_KEY` (optional)
Baidu Api Key.
### `BAIDU_SECRET_KEY` (optional)
Baidu Secret Key.
### `BAIDU_URL` (optional)
Baidu Api Url.
### `BYTEDANCE_API_KEY` (optional)
ByteDance Api Key.
### `BYTEDANCE_URL` (optional)
ByteDance Api Url.
### `ALIBABA_API_KEY` (optional)
Alibaba Cloud Api Key.
### `ALIBABA_URL` (optional)
Alibaba Cloud Api Url.
### `IFLYTEK_URL` (Optional)
iflytek Api Url.
### `IFLYTEK_API_KEY` (Optional)
iflytek Api Key.
### `IFLYTEK_API_SECRET` (Optional)
iflytek Api Secret.
deepseek Api Key.
### `HIDE_USER_API_KEY` (optional)
@@ -329,36 +249,14 @@ To control custom models, use `+` to add a custom model, use `-` to hide a model
User `-all` to disable all default models, `+all` to enable all default models.
For Azure: use `modelName@azure=deploymentName` to customize model name and deployment name.
> Example: `+gpt-3.5-turbo@azure=gpt35` will show option `gpt35(Azure)` in model list.
> If you only can use Azure model, `-all,+gpt-3.5-turbo@azure=gpt35` will `gpt35(Azure)` the only option in model list.
For ByteDance: use `modelName@bytedance=deploymentName` to customize model name and deployment name.
> Example: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` will show option `Doubao-lite-4k(ByteDance)` in model list.
### `DEFAULT_MODEL` optional
Change default model
### `WHITE_WEBDEV_ENDPOINTS` (optional)
### `WEBDEV_ENDPOINTS_WHITELIST` (可选)
You can use this option if you want to increase the number of webdav service addresses you are allowed to access, as required by the format
- Each address must be a complete endpoint
> `https://xxxx/yyy`
- Each address must be a complete endpoint
> `https://xxxx/yyy`
- Multiple addresses are connected by ', '
### `DEFAULT_INPUT_TEMPLATE` (optional)
Customize the default template used to initialize the User Input Preprocessing configuration item in Settings.
### `STABILITY_API_KEY` (optional)
Stability API key.
### `STABILITY_URL` (optional)
Customize Stability API url.
## Requirements
NodeJS >= 18, Docker >= 20

View File

@@ -1,34 +1,22 @@
<div align="center">
<a href='#企业版'>
<img src="./docs/images/ent.svg" alt="icon"/>
</a>
<img src="./docs/images/icon.svg" alt="预览"/>
<h1 align="center">NextChat</h1>
一键免费部署你的私人 ChatGPT 网页应用,支持 GPT3, GPT4 & Gemini Pro 模型。
[企业版](#%E4%BC%81%E4%B8%9A%E7%89%88) /[演示 Demo](https://chat-gpt-next-web.vercel.app/) / [反馈 Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [加入 Discord](https://discord.gg/zrhvHCr79N)
[演示 Demo](https://chat-gpt-next-web.vercel.app/) / [反馈 Issues](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [加入 Discord](https://discord.gg/zrhvHCr79N)
[<img src="https://vercel.com/button" alt="Deploy on Zeabur" height="30">](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat) [<img src="https://zeabur.com/button.svg" alt="Deploy on Zeabur" height="30">](https://zeabur.com/templates/ZBUEFA) [<img src="https://gitpod.io/button/open-in-gitpod.svg" alt="Open in Gitpod" height="30">](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web)
[![Deploy on Zeabur](https://zeabur.com/button.svg)](https://zeabur.com/templates/ZBUEFA)
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
![主界面](./docs/images/cover.png)
</div>
## 企业版
满足您公司私有化部署和定制需求
- **品牌定制**:企业量身定制 VI/UI与企业品牌形象无缝契合
- **资源集成**:由企业管理人员统一配置和管理数十种 AI 资源,团队成员开箱即用
- **权限管理**:成员权限、资源权限、知识库权限层级分明,企业级 Admin Panel 统一控制
- **知识接入**:企业内部知识库与 AI 能力相结合,比通用 AI 更贴近企业自身业务需求
- **安全审计**:自动拦截敏感提问,支持追溯全部历史对话记录,让 AI 也能遵循企业信息安全规范
- **私有部署**:企业级私有部署,支持各类主流私有云部署,确保数据安全和隐私保护
- **持续更新**:提供多模态、智能体等前沿能力持续更新升级服务,常用常新、持续先进
企业版咨询: **business@nextchat.dev**
<img width="300" src="https://github.com/user-attachments/assets/3daeb7b6-ab63-4542-9141-2e4a12c80601">
## 开始使用
1. 准备好你的 [OpenAI API Key](https://platform.openai.com/account/api-keys);
@@ -37,12 +25,6 @@
3. 部署完毕后,即可开始使用;
4. (可选)[绑定自定义域名](https://vercel.com/docs/concepts/projects/domains/add-a-domain)Vercel 分配的域名 DNS 在某些区域被污染了,绑定自定义域名即可直连。
<div align="center">
![主界面](./docs/images/cover.png)
</div>
## 保持更新
如果你按照上述步骤一键部署了自己的项目,可能会发现总是提示“存在更新”的问题,这是由于 Vercel 会默认为你创建一个新项目而不是 fork 本项目,这会导致无法正确地检测更新。
@@ -112,7 +94,7 @@ OpenAI 接口代理 URL如果你手动配置了 openai 接口代理,请填
### `AZURE_URL` (可选)
> 形如https://{azure-resource-url}/openai
> 形如https://{azure-resource-url}/openai/deployments/{deploy-name}
Azure 部署地址。
@@ -124,67 +106,29 @@ Azure 密钥。
Azure Api 版本,你可以在这里找到:[Azure 文档](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions)。
### `GOOGLE_API_KEY` (可选)
### `GOOGLE_API_KEY` (optional)
Google Gemini Pro 密钥.
### `GOOGLE_URL` (可选)
### `GOOGLE_URL` (optional)
Google Gemini Pro Api Url.
### `ANTHROPIC_API_KEY` (可选)
### `ANTHROPIC_API_KEY` (optional)
anthropic claude Api Key.
### `ANTHROPIC_API_VERSION` (可选)
### `ANTHROPIC_API_VERSION` (optional)
anthropic claude Api version.
### `ANTHROPIC_URL` (可选)
### `ANTHROPIC_URL` (optional)
anthropic claude Api Url.
### `BAIDU_API_KEY` (可选)
Baidu Api Key.
### `BAIDU_SECRET_KEY` (可选)
Baidu Secret Key.
### `BAIDU_URL` (可选)
Baidu Api Url.
### `BYTEDANCE_API_KEY` (可选)
ByteDance Api Key.
### `BYTEDANCE_URL` (可选)
ByteDance Api Url.
### `ALIBABA_API_KEY` (可选)
阿里云千问Api Key.
### `ALIBABA_URL` (可选)
阿里云千问Api Url.
### `IFLYTEK_URL` (可选)
讯飞星火Api Url.
### `IFLYTEK_API_KEY` (可选)
讯飞星火Api Key.
### `IFLYTEK_API_SECRET` (可选)
讯飞星火Api Secret.
### `DEEPSEEK_API_KEY` (optional)
deepseek Api Key.
### `HIDE_USER_API_KEY` (可选)
@@ -202,11 +146,12 @@ ByteDance Api Url.
如果你想禁用从链接解析预制设置,将此环境变量设置为 1 即可。
### `WHITE_WEBDEV_ENDPOINTS` (可选)
### `WEBDEV_ENDPOINTS_WHITELIST` (可选)
如果你想增加允许访问的webdav服务地址可以使用该选项格式要求
- 每一个地址必须是一个完整的 endpoint
> `https://xxxx/xxx`
> `https://xxxx/xxx`
- 多个地址以`,`相连
### `CUSTOM_MODELS` (可选)
@@ -216,31 +161,6 @@ ByteDance Api Url.
用来控制模型列表,使用 `+` 增加一个模型,使用 `-` 来隐藏一个模型,使用 `模型名=展示名` 来自定义模型的展示名,用英文逗号隔开。
在Azure的模式下支持使用`modelName@azure=deploymentName`的方式配置模型名称和部署名称(deploy-name)
> 示例:`+gpt-3.5-turbo@azure=gpt35`这个配置会在模型列表显示一个`gpt35(Azure)`的选项。
> 如果你只能使用Azure模式那么设置 `-all,+gpt-3.5-turbo@azure=gpt35` 则可以让对话的默认使用 `gpt35(Azure)`
在ByteDance的模式下支持使用`modelName@bytedance=deploymentName`的方式配置模型名称和部署名称(deploy-name)
> 示例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx`这个配置会在模型列表显示一个`Doubao-lite-4k(ByteDance)`的选项
### `DEFAULT_MODEL` (可选)
更改默认模型
### `DEFAULT_INPUT_TEMPLATE` (可选)
自定义默认的 template用于初始化『设置』中的『用户输入预处理』配置项
### `STABILITY_API_KEY` (optional)
Stability API密钥
### `STABILITY_URL` (optional)
自定义的Stability API请求地址
## 开发
点击下方按钮,开始二次开发:

View File

@@ -1,310 +0,0 @@
<div align="center">
<img src="./docs/images/ent.svg" alt="プレビュー"/>
<h1 align="center">NextChat</h1>
ワンクリックで無料であなた専用の ChatGPT ウェブアプリをデプロイ。GPT3、GPT4 & Gemini Pro モデルをサポート。
[企業版](#企業版) / [デモ](https://chat-gpt-next-web.vercel.app/) / [フィードバック](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [Discordに参加](https://discord.gg/zrhvHCr79N)
[<img src="https://vercel.com/button" alt="Zeaburでデプロイ" height="30">](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FChatGPTNextWeb%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&project-name=nextchat&repository-name=NextChat) [<img src="https://zeabur.com/button.svg" alt="Zeaburでデプロイ" height="30">](https://zeabur.com/templates/ZBUEFA) [<img src="https://gitpod.io/button/open-in-gitpod.svg" alt="Gitpodで開く" height="30">](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
</div>
## 企業版
あなたの会社のプライベートデプロイとカスタマイズのニーズに応える
- **ブランドカスタマイズ**:企業向けに特別に設計された VI/UI、企業ブランドイメージとシームレスにマッチ
- **リソース統合**企業管理者が数十種類のAIリソースを統一管理、チームメンバーはすぐに使用可能
- **権限管理**メンバーの権限、リソースの権限、ナレッジベースの権限を明確にし、企業レベルのAdmin Panelで統一管理
- **知識の統合**企業内部のナレッジベースとAI機能を結びつけ、汎用AIよりも企業自身の業務ニーズに近づける
- **セキュリティ監査**機密質問を自動的にブロックし、すべての履歴対話を追跡可能にし、AIも企業の情報セキュリティ基準に従わせる
- **プライベートデプロイ**:企業レベルのプライベートデプロイ、主要なプライベートクラウドデプロイをサポートし、データのセキュリティとプライバシーを保護
- **継続的な更新**:マルチモーダル、エージェントなどの最先端機能を継続的に更新し、常に最新であり続ける
企業版のお問い合わせ: **business@nextchat.dev**
## 始めに
1. [OpenAI API Key](https://platform.openai.com/account/api-keys)を準備する;
2. 右側のボタンをクリックしてデプロイを開始:
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYidadaa%2FChatGPT-Next-Web&env=OPENAI_API_KEY&env=CODE&env=GOOGLE_API_KEY&project-name=chatgpt-next-web&repository-name=ChatGPT-Next-Web) 、GitHubアカウントで直接ログインし、環境変数ページにAPI Keyと[ページアクセスパスワード](#設定ページアクセスパスワード) CODEを入力してください;
3. デプロイが完了したら、すぐに使用を開始できます;
4. (オプション)[カスタムドメインをバインド](https://vercel.com/docs/concepts/projects/domains/add-a-domain)Vercelが割り当てたドメインDNSは一部の地域で汚染されているため、カスタムドメインをバインドすると直接接続できます。
<div align="center">
![メインインターフェース](./docs/images/cover.png)
</div>
## 更新を維持する
もし上記の手順に従ってワンクリックでプロジェクトをデプロイした場合、「更新があります」というメッセージが常に表示されることがあります。これは、Vercel がデフォルトで新しいプロジェクトを作成するためで、本プロジェクトを fork していないことが原因です。そのため、正しく更新を検出できません。
以下の手順に従って再デプロイすることをお勧めします:
- 元のリポジトリを削除する
- ページ右上の fork ボタンを使って、本プロジェクトを fork する
- Vercel で再度選択してデプロイする、[詳細な手順はこちらを参照してください](./docs/vercel-ja.md)。
### 自動更新を開く
> Upstream Sync の実行エラーが発生した場合は、手動で Sync Fork してください!
プロジェクトを fork した後、GitHub の制限により、fork 後のプロジェクトの Actions ページで Workflows を手動で有効にし、Upstream Sync Action を有効にする必要があります。有効化後、毎時の定期自動更新が可能になります:
![自動更新](./docs/images/enable-actions.jpg)
![自動更新を有効にする](./docs/images/enable-actions-sync.jpg)
### 手動でコードを更新する
手動で即座に更新したい場合は、[GitHub のドキュメント](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/syncing-a-fork)を参照して、fork したプロジェクトを上流のコードと同期する方法を確認してください。
このプロジェクトをスターまたはウォッチしたり、作者をフォローすることで、新機能の更新通知をすぐに受け取ることができます。
## ページアクセスパスワードを設定する
> パスワードを設定すると、ユーザーは設定ページでアクセスコードを手動で入力しない限り、通常のチャットができず、未承認の状態であることを示すメッセージが表示されます。
> **警告**パスワードの桁数は十分に長く設定してください。7桁以上が望ましいです。さもないと、[ブルートフォース攻撃を受ける可能性があります](https://github.com/Yidadaa/ChatGPT-Next-Web/issues/518)。
このプロジェクトは限られた権限管理機能を提供しています。Vercel プロジェクトのコントロールパネルで、環境変数ページに `CODE` という名前の環境変数を追加し、値をカンマで区切ったカスタムパスワードに設定してください:
```
code1,code2,code3
```
この環境変数を追加または変更した後、**プロジェクトを再デプロイ**して変更を有効にしてください。
## 環境変数
> 本プロジェクトのほとんどの設定は環境変数で行います。チュートリアル:[Vercel の環境変数を変更する方法](./docs/vercel-ja.md)。
### `OPENAI_API_KEY` (必須)
OpenAI の API キー。OpenAI アカウントページで申請したキーをカンマで区切って複数設定できます。これにより、ランダムにキーが選択されます。
### `CODE` (オプション)
アクセスパスワード。カンマで区切って複数設定可能。
**警告**:この項目を設定しないと、誰でもデプロイしたウェブサイトを利用でき、トークンが急速に消耗する可能性があるため、設定をお勧めします。
### `BASE_URL` (オプション)
> デフォルト: `https://api.openai.com`
> 例: `http://your-openai-proxy.com`
OpenAI API のプロキシ URL。手動で OpenAI API のプロキシを設定している場合はこのオプションを設定してください。
> SSL 証明書の問題がある場合は、`BASE_URL` のプロトコルを http に設定してください。
### `OPENAI_ORG_ID` (オプション)
OpenAI の組織 ID を指定します。
### `AZURE_URL` (オプション)
> 形式: https://{azure-resource-url}/openai/deployments/{deploy-name}
> `CUSTOM_MODELS` で `displayName` 形式で {deploy-name} を設定した場合、`AZURE_URL` から {deploy-name} を省略できます。
Azure のデプロイ URL。
### `AZURE_API_KEY` (オプション)
Azure の API キー。
### `AZURE_API_VERSION` (オプション)
Azure API バージョン。[Azure ドキュメント](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions)で確認できます。
### `GOOGLE_API_KEY` (オプション)
Google Gemini Pro API キー。
### `GOOGLE_URL` (オプション)
Google Gemini Pro API の URL。
### `ANTHROPIC_API_KEY` (オプション)
Anthropic Claude API キー。
### `ANTHROPIC_API_VERSION` (オプション)
Anthropic Claude API バージョン。
### `ANTHROPIC_URL` (オプション)
Anthropic Claude API の URL。
### `BAIDU_API_KEY` (オプション)
Baidu API キー。
### `BAIDU_SECRET_KEY` (オプション)
Baidu シークレットキー。
### `BAIDU_URL` (オプション)
Baidu API の URL。
### `BYTEDANCE_API_KEY` (オプション)
ByteDance API キー。
### `BYTEDANCE_URL` (オプション)
ByteDance API の URL。
### `ALIBABA_API_KEY` (オプション)
アリババ千问API キー。
### `ALIBABA_URL` (オプション)
アリババ千问API の URL。
### `HIDE_USER_API_KEY` (オプション)
ユーザーが API キーを入力できないようにしたい場合は、この環境変数を 1 に設定します。
### `DISABLE_GPT4` (オプション)
ユーザーが GPT-4 を使用できないようにしたい場合は、この環境変数を 1 に設定します。
### `ENABLE_BALANCE_QUERY` (オプション)
バランスクエリ機能を有効にしたい場合は、この環境変数を 1 に設定します。
### `DISABLE_FAST_LINK` (オプション)
リンクからのプリセット設定解析を無効にしたい場合は、この環境変数を 1 に設定します。
### `WHITE_WEBDEV_ENDPOINTS` (オプション)
アクセス許可を与える WebDAV サービスのアドレスを追加したい場合、このオプションを使用します。フォーマット要件:
- 各アドレスは完全なエンドポイントでなければなりません。
> `https://xxxx/xxx`
- 複数のアドレスは `,` で接続します。
### `CUSTOM_MODELS` (オプション)
> 例:`+qwen-7b-chat,+glm-6b,-gpt-3.5-turbo,gpt-4-1106-preview=gpt-4-turbo` は `qwen-7b-chat` と `glm-6b` をモデルリストに追加し、`gpt-3.5-turbo` を削除し、`gpt-4-1106-preview` のモデル名を `gpt-4-turbo` として表示します。
> すべてのモデルを無効にし、特定のモデルを有効にしたい場合は、`-all,+gpt-3.5-turbo` を使用します。これは `gpt-3.5-turbo` のみを有効にすることを意味します。
モデルリストを管理します。`+` でモデルを追加し、`-` でモデルを非表示にし、`モデル名=表示名` でモデルの表示名をカスタマイズし、カンマで区切ります。
Azure モードでは、`modelName@azure=deploymentName` 形式でモデル名とデプロイ名deploy-nameを設定できます。
> 例:`+gpt-3.5-turbo@azure=gpt35` この設定でモデルリストに `gpt35(Azure)` のオプションが表示されます。
ByteDance モードでは、`modelName@bytedance=deploymentName` 形式でモデル名とデプロイ名deploy-nameを設定できます。
> 例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` この設定でモデルリストに `Doubao-lite-4k(ByteDance)` のオプションが表示されます。
### `DEFAULT_MODEL` (オプション)
デフォルトのモデルを変更します。
### `DEFAULT_INPUT_TEMPLATE` (オプション)
『設定』の『ユーザー入力前処理』の初期設定に使用するテンプレートをカスタマイズします。
## 開発
下のボタンをクリックして二次開発を開始してください:
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/Yidadaa/ChatGPT-Next-Web)
コードを書く前に、プロジェクトのルートディレクトリに `.env.local` ファイルを新規作成し、環境変数を記入します:
```
OPENAI_API_KEY=<your api key here>
```
### ローカル開発
1. Node.js 18 と Yarn をインストールします。具体的な方法は ChatGPT にお尋ねください。
2. `yarn install && yarn dev` を実行します。⚠️ 注意:このコマンドはローカル開発用であり、デプロイには使用しないでください。
3. ローカルでデプロイしたい場合は、`yarn install && yarn build && yarn start` コマンドを使用してください。プロセスを守るために pm2 を使用することもできます。詳細は ChatGPT にお尋ねください。
## デプロイ
### コンテナデプロイ(推奨)
> Docker バージョンは 20 以上が必要です。それ以下だとイメージが見つからないというエラーが出ます。
> ⚠️ 注意Docker バージョンは最新バージョンより 12 日遅れることが多いため、デプロイ後に「更新があります」の通知が出続けることがありますが、正常です。
```shell
docker pull yidadaa/chatgpt-next-web
docker run -d -p 3000:3000 \
-e OPENAI_API_KEY=sk-xxxx \
-e CODE=ページアクセスパスワード \
yidadaa/chatgpt-next-web
```
プロキシを指定することもできます:
```shell
docker run -d -p 3000:3000 \
-e OPENAI_API_KEY=sk-xxxx \
-e CODE=ページアクセスパスワード \
--net=host \
-e PROXY_URL=http://127.0.0.1:7890 \
yidadaa/chatgpt-next-web
```
ローカルプロキシがアカウントとパスワードを必要とする場合は、以下を使用できます:
```shell
-e PROXY_URL="http://127.0.0.1:7890 user password"
```
他の環境変数を指定する必要がある場合は、上記のコマンドに `-e 環境変数=環境変数値` を追加して指定してください。
### ローカルデプロイ
コンソールで以下のコマンドを実行します:
```shell
bash <(curl -s https://raw.githubusercontent.com/Yidadaa/ChatGPT-Next-Web/main/scripts/setup.sh)
```
⚠️ 注意インストール中に問題が発生した場合は、Docker を使用してデプロイしてください。
## 謝辞
### 寄付者
> 英語版をご覧ください。
### 貢献者
[プロジェクトの貢献者リストはこちら](https://github.com/Yidadaa/ChatGPT-Next-Web/graphs/contributors)
### 関連プロジェクト
- [one-api](https://github.com/songquanpeng/one-api): 一つのプラットフォームで大規模モデルのクォータ管理を提供し、市場に出回っているすべての主要な大規模言語モデルをサポートします。
## オープンソースライセンス
[MIT](https://opensource.org/license/mit/)

View File

@@ -1,70 +0,0 @@
import { ApiPath } from "@/app/constant";
import { NextRequest, NextResponse } from "next/server";
import { handle as openaiHandler } from "../../openai";
import { handle as azureHandler } from "../../azure";
import { handle as googleHandler } from "../../google";
import { handle as anthropicHandler } from "../../anthropic";
import { handle as baiduHandler } from "../../baidu";
import { handle as bytedanceHandler } from "../../bytedance";
import { handle as alibabaHandler } from "../../alibaba";
import { handle as moonshotHandler } from "../../moonshot";
import { handle as stabilityHandler } from "../../stability";
import { handle as iflytekHandler } from "../../iflytek";
import { handle as proxyHandler } from "../../proxy";
async function handle(
req: NextRequest,
{ params }: { params: { provider: string; path: string[] } },
) {
const apiPath = `/api/${params.provider}`;
console.log(`[${params.provider} Route] params `, params);
switch (apiPath) {
case ApiPath.Azure:
return azureHandler(req, { params });
case ApiPath.Google:
return googleHandler(req, { params });
case ApiPath.Anthropic:
return anthropicHandler(req, { params });
case ApiPath.Baidu:
return baiduHandler(req, { params });
case ApiPath.ByteDance:
return bytedanceHandler(req, { params });
case ApiPath.Alibaba:
return alibabaHandler(req, { params });
// case ApiPath.Tencent: using "/api/tencent"
case ApiPath.Moonshot:
return moonshotHandler(req, { params });
case ApiPath.Stability:
return stabilityHandler(req, { params });
case ApiPath.Iflytek:
return iflytekHandler(req, { params });
case ApiPath.OpenAI:
return openaiHandler(req, { params });
default:
return proxyHandler(req, { params });
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
export const preferredRegion = [
"arn1",
"bom1",
"cdg1",
"cle1",
"cpt1",
"dub1",
"fra1",
"gru1",
"hnd1",
"iad1",
"icn1",
"kix1",
"lhr1",
"pdx1",
"sfo1",
"sin1",
"syd1",
];

View File

@@ -1,131 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import {
Alibaba,
ALIBABA_BASE_URL,
ApiPath,
ModelProvider,
ServiceProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/app/api/auth";
import { isModelAvailableInServer } from "@/app/utils/model";
import type { RequestPayload } from "@/app/client/platforms/openai";
const serverConfig = getServerSideConfig();
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Alibaba Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const authResult = auth(req, ModelProvider.Qwen);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
try {
const response = await request(req);
return response;
} catch (e) {
console.error("[Alibaba] ", e);
return NextResponse.json(prettyObject(e));
}
}
async function request(req: NextRequest) {
const controller = new AbortController();
// alibaba use base url or just remove the path
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Alibaba, "");
let baseUrl = serverConfig.alibabaUrl || ALIBABA_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = `${baseUrl}${path}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
Authorization: req.headers.get("Authorization") ?? "",
"X-DashScope-SSE": req.headers.get("X-DashScope-SSE") ?? "disable",
},
method: req.method,
body: req.body,
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
// #1815 try to refuse some request to some models
if (serverConfig.customModels && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.Alibaba as string,
)
) {
return NextResponse.json(
{
error: true,
message: `you are not allowed to use ${jsonBody?.model} model`,
},
{
status: 403,
},
);
}
} catch (e) {
console.error(`[Alibaba] filter`, e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -4,18 +4,16 @@ import {
Anthropic,
ApiPath,
DEFAULT_MODELS,
ServiceProvider,
ModelProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "./auth";
import { isModelAvailableInServer } from "@/app/utils/model";
import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
import { auth } from "../../auth";
import { collectModelTable } from "@/app/utils/model";
const ALLOWD_PATH = new Set([Anthropic.ChatPath, Anthropic.ChatPath1]);
export async function handle(
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
@@ -56,6 +54,30 @@ export async function handle(
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
export const preferredRegion = [
"arn1",
"bom1",
"cdg1",
"cle1",
"cpt1",
"dub1",
"fra1",
"gru1",
"hnd1",
"iad1",
"icn1",
"kix1",
"lhr1",
"pdx1",
"sfo1",
"sin1",
"syd1",
];
const serverConfig = getServerSideConfig();
async function request(req: NextRequest) {
@@ -91,8 +113,7 @@ async function request(req: NextRequest) {
10 * 60 * 1000,
);
// try rebuild url, when using cloudflare ai gateway in server
const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}${path}`);
const fetchUrl = `${baseUrl}${path}`;
const fetchOptions: RequestInit = {
headers: {
@@ -115,19 +136,17 @@ async function request(req: NextRequest) {
// #1815 try to refuse some request to some models
if (serverConfig.customModels && req.body) {
try {
const modelTable = collectModelTable(
DEFAULT_MODELS,
serverConfig.customModels,
);
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.Anthropic as string,
)
) {
if (modelTable[jsonBody?.model ?? ""].available === false) {
return NextResponse.json(
{
error: true,
@@ -142,17 +161,17 @@ async function request(req: NextRequest) {
console.error(`[Anthropic] filter`, e);
}
}
// console.log("[Anthropic request]", fetchOptions.headers, req.method);
console.log("[Anthropic request]", fetchOptions.headers, req.method);
try {
const res = await fetch(fetchUrl, fetchOptions);
// console.log(
// "[Anthropic response]",
// res.status,
// " ",
// res.headers,
// res.url,
// );
console.log(
"[Anthropic response]",
res.status,
" ",
res.headers,
res.url,
);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");

View File

@@ -1,73 +0,0 @@
import md5 from "spark-md5";
import { NextRequest, NextResponse } from "next/server";
import { getServerSideConfig } from "@/app/config/server";
async function handle(req: NextRequest, res: NextResponse) {
const serverConfig = getServerSideConfig();
const storeUrl = () =>
`https://api.cloudflare.com/client/v4/accounts/${serverConfig.cloudflareAccountId}/storage/kv/namespaces/${serverConfig.cloudflareKVNamespaceId}`;
const storeHeaders = () => ({
Authorization: `Bearer ${serverConfig.cloudflareKVApiKey}`,
});
if (req.method === "POST") {
const clonedBody = await req.text();
const hashedCode = md5.hash(clonedBody).trim();
const body: {
key: string;
value: string;
expiration_ttl?: number;
} = {
key: hashedCode,
value: clonedBody,
};
try {
const ttl = parseInt(serverConfig.cloudflareKVTTL as string);
if (ttl > 60) {
body["expiration_ttl"] = ttl;
}
} catch (e) {
console.error(e);
}
const res = await fetch(`${storeUrl()}/bulk`, {
headers: {
...storeHeaders(),
"Content-Type": "application/json",
},
method: "PUT",
body: JSON.stringify([body]),
});
const result = await res.json();
console.log("save data", result);
if (result?.success) {
return NextResponse.json(
{ code: 0, id: hashedCode, result },
{ status: res.status },
);
}
return NextResponse.json(
{ error: true, msg: "Save data error" },
{ status: 400 },
);
}
if (req.method === "GET") {
const id = req?.nextUrl?.searchParams?.get("id");
const res = await fetch(`${storeUrl()}/values/${id}`, {
headers: storeHeaders(),
method: "GET",
});
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: res.headers,
});
}
return NextResponse.json(
{ error: true, msg: "Invalid request" },
{ status: 400 },
);
}
export const POST = handle;
export const GET = handle;
export const runtime = "edge";

View File

@@ -67,34 +67,19 @@ export function auth(req: NextRequest, modelProvider: ModelProvider) {
let systemApiKey: string | undefined;
switch (modelProvider) {
case ModelProvider.Stability:
systemApiKey = serverConfig.stabilityApiKey;
break;
case ModelProvider.GeminiPro:
systemApiKey = serverConfig.googleApiKey;
break;
case ModelProvider.Claude:
systemApiKey = serverConfig.anthropicApiKey;
break;
case ModelProvider.Doubao:
systemApiKey = serverConfig.bytedanceApiKey;
break;
case ModelProvider.Ernie:
systemApiKey = serverConfig.baiduApiKey;
break;
case ModelProvider.Qwen:
systemApiKey = serverConfig.alibabaApiKey;
break;
case ModelProvider.Moonshot:
systemApiKey = serverConfig.moonshotApiKey;
break;
case ModelProvider.Iflytek:
systemApiKey =
serverConfig.iflytekApiKey + ":" + serverConfig.iflytekApiSecret;
case ModelProvider.Deepseek:
systemApiKey = serverConfig.deepseekApiKey;
break;
case ModelProvider.GPT:
default:
if (req.nextUrl.pathname.includes("azure/deployments")) {
if (serverConfig.isAzure) {
systemApiKey = serverConfig.azureApiKey;
} else {
systemApiKey = serverConfig.apiKey;

View File

@@ -1,33 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import { ModelProvider } from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "./auth";
import { requestOpenai } from "./common";
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Azure Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const subpath = params.path.join("/");
const authResult = auth(req, ModelProvider.GPT);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
try {
return await requestOpenai(req);
} catch (e) {
console.error("[Azure] ", e);
return NextResponse.json(prettyObject(e));
}
}

View File

@@ -1,145 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import {
BAIDU_BASE_URL,
ApiPath,
ModelProvider,
BAIDU_OATUH_URL,
ServiceProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/app/api/auth";
import { isModelAvailableInServer } from "@/app/utils/model";
import { getAccessToken } from "@/app/utils/baidu";
const serverConfig = getServerSideConfig();
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Baidu Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const authResult = auth(req, ModelProvider.Ernie);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
if (!serverConfig.baiduApiKey || !serverConfig.baiduSecretKey) {
return NextResponse.json(
{
error: true,
message: `missing BAIDU_API_KEY or BAIDU_SECRET_KEY in server env vars`,
},
{
status: 401,
},
);
}
try {
const response = await request(req);
return response;
} catch (e) {
console.error("[Baidu] ", e);
return NextResponse.json(prettyObject(e));
}
}
async function request(req: NextRequest) {
const controller = new AbortController();
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Baidu, "");
let baseUrl = serverConfig.baiduUrl || BAIDU_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const { access_token } = await getAccessToken(
serverConfig.baiduApiKey as string,
serverConfig.baiduSecretKey as string,
);
const fetchUrl = `${baseUrl}${path}?access_token=${access_token}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
},
method: req.method,
body: req.body,
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
// #1815 try to refuse some request to some models
if (serverConfig.customModels && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.Baidu as string,
)
) {
return NextResponse.json(
{
error: true,
message: `you are not allowed to use ${jsonBody?.model} model`,
},
{
status: 403,
},
);
}
} catch (e) {
console.error(`[Baidu] filter`, e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -1,129 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import {
BYTEDANCE_BASE_URL,
ApiPath,
ModelProvider,
ServiceProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/app/api/auth";
import { isModelAvailableInServer } from "@/app/utils/model";
const serverConfig = getServerSideConfig();
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[ByteDance Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const authResult = auth(req, ModelProvider.Doubao);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
try {
const response = await request(req);
return response;
} catch (e) {
console.error("[ByteDance] ", e);
return NextResponse.json(prettyObject(e));
}
}
async function request(req: NextRequest) {
const controller = new AbortController();
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ByteDance, "");
let baseUrl = serverConfig.bytedanceUrl || BYTEDANCE_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = `${baseUrl}${path}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
Authorization: req.headers.get("Authorization") ?? "",
},
method: req.method,
body: req.body,
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
// #1815 try to refuse some request to some models
if (serverConfig.customModels && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.ByteDance as string,
)
) {
return NextResponse.json(
{
error: true,
message: `you are not allowed to use ${jsonBody?.model} model`,
},
{
status: 403,
},
);
}
} catch (e) {
console.error(`[ByteDance] filter`, e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -1,24 +1,17 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSideConfig } from "../config/server";
import {
DEFAULT_MODELS,
OPENAI_BASE_URL,
GEMINI_BASE_URL,
ServiceProvider,
} from "../constant";
import { isModelAvailableInServer } from "../utils/model";
import { cloudflareAIGatewayUrl } from "../utils/cloudflare";
import { DEFAULT_MODELS, OPENAI_BASE_URL, GEMINI_BASE_URL } from "../constant";
import { collectModelTable } from "../utils/model";
import { makeAzurePath } from "../azure";
const serverConfig = getServerSideConfig();
export async function requestOpenai(req: NextRequest) {
const controller = new AbortController();
const isAzure = req.nextUrl.pathname.includes("azure/deployments");
var authValue,
authHeaderName = "";
if (isAzure) {
if (serverConfig.isAzure) {
authValue =
req.headers
.get("Authorization")
@@ -32,10 +25,13 @@ export async function requestOpenai(req: NextRequest) {
authHeaderName = "Authorization";
}
let path = `${req.nextUrl.pathname}`.replaceAll("/api/openai/", "");
let path = `${req.nextUrl.pathname}${req.nextUrl.search}`.replaceAll(
"/api/openai/",
"",
);
let baseUrl =
(isAzure ? serverConfig.azureUrl : serverConfig.baseUrl) || OPENAI_BASE_URL;
serverConfig.azureUrl || serverConfig.baseUrl || OPENAI_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
@@ -55,46 +51,17 @@ export async function requestOpenai(req: NextRequest) {
10 * 60 * 1000,
);
if (isAzure) {
const azureApiVersion =
req?.nextUrl?.searchParams?.get("api-version") ||
serverConfig.azureApiVersion;
baseUrl = baseUrl.split("/deployments").shift() as string;
path = `${req.nextUrl.pathname.replaceAll(
"/api/azure/",
"",
)}?api-version=${azureApiVersion}`;
// Forward compatibility:
// if display_name(deployment_name) not set, and '{deploy-id}' in AZURE_URL
// then using default '{deploy-id}'
if (serverConfig.customModels && serverConfig.azureUrl) {
const modelName = path.split("/")[1];
let realDeployName = "";
serverConfig.customModels
.split(",")
.filter((v) => !!v && !v.startsWith("-") && v.includes(modelName))
.forEach((m) => {
const [fullName, displayName] = m.split("=");
const [_, providerName] = fullName.split("@");
if (providerName === "azure" && !displayName) {
const [_, deployId] = (serverConfig?.azureUrl ?? "").split(
"deployments/",
);
if (deployId) {
realDeployName = deployId;
}
}
});
if (realDeployName) {
console.log("[Replace with DeployId", realDeployName);
path = path.replaceAll(modelName, realDeployName);
}
if (serverConfig.isAzure) {
if (!serverConfig.azureApiVersion) {
return NextResponse.json({
error: true,
message: `missing AZURE_API_VERSION in server env vars`,
});
}
path = makeAzurePath(path, serverConfig.azureApiVersion);
}
const fetchUrl = cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
console.log("fetchUrl", fetchUrl);
const fetchUrl = `${baseUrl}/${path}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
@@ -116,24 +83,19 @@ export async function requestOpenai(req: NextRequest) {
// #1815 try to refuse gpt4 request
if (serverConfig.customModels && req.body) {
try {
const modelTable = collectModelTable(
DEFAULT_MODELS,
serverConfig.customModels,
);
// check if deepseek model
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.OpenAI as string,
) ||
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.Azure as string,
)
) {
if (modelTable[jsonBody?.model ?? ""].available === false) {
return NextResponse.json(
{
error: true,

View File

@@ -1,19 +1,11 @@
import { NextRequest, NextResponse } from "next/server";
import { auth } from "./auth";
import { auth } from "../../auth";
import { getServerSideConfig } from "@/app/config/server";
import {
ApiPath,
GEMINI_BASE_URL,
Google,
ModelProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { GEMINI_BASE_URL, Google, ModelProvider } from "@/app/constant";
const serverConfig = getServerSideConfig();
export async function handle(
async function handle(
req: NextRequest,
{ params }: { params: { provider: string; path: string[] } },
{ params }: { params: { path: string[] } },
) {
console.log("[Google Route] params ", params);
@@ -21,6 +13,32 @@ export async function handle(
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const controller = new AbortController();
const serverConfig = getServerSideConfig();
let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
let path = `${req.nextUrl.pathname}`.replaceAll("/api/google/", "");
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const authResult = auth(req, ModelProvider.GeminiPro);
if (authResult.error) {
return NextResponse.json(authResult, {
@@ -31,9 +49,9 @@ export async function handle(
const bearToken = req.headers.get("Authorization") ?? "";
const token = bearToken.trim().replaceAll("Bearer ", "").trim();
const apiKey = token ? token : serverConfig.googleApiKey;
const key = token ? token : serverConfig.googleApiKey;
if (!apiKey) {
if (!key) {
return NextResponse.json(
{
error: true,
@@ -44,63 +62,8 @@ export async function handle(
},
);
}
try {
const response = await request(req, apiKey);
return response;
} catch (e) {
console.error("[Google] ", e);
return NextResponse.json(prettyObject(e));
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
export const preferredRegion = [
"bom1",
"cle1",
"cpt1",
"gru1",
"hnd1",
"iad1",
"icn1",
"kix1",
"pdx1",
"sfo1",
"sin1",
"syd1",
];
async function request(req: NextRequest, apiKey: string) {
const controller = new AbortController();
let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Google, "");
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = `${baseUrl}${path}?key=${apiKey}${
req?.nextUrl?.searchParams?.get("alt") === "sse" ? "&alt=sse" : ""
}`;
console.log("[Fetch Url] ", fetchUrl);
const fetchUrl = `${baseUrl}/${path}?key=${key}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
@@ -132,3 +95,22 @@ async function request(req: NextRequest, apiKey: string) {
clearTimeout(timeoutId);
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
export const preferredRegion = [
"bom1",
"cle1",
"cpt1",
"gru1",
"hnd1",
"iad1",
"icn1",
"kix1",
"pdx1",
"sfo1",
"sin1",
"syd1",
];

View File

@@ -1,131 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import {
Iflytek,
IFLYTEK_BASE_URL,
ApiPath,
ModelProvider,
ServiceProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/app/api/auth";
import { isModelAvailableInServer } from "@/app/utils/model";
import type { RequestPayload } from "@/app/client/platforms/openai";
// iflytek
const serverConfig = getServerSideConfig();
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Iflytek Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const authResult = auth(req, ModelProvider.Iflytek);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
try {
const response = await request(req);
return response;
} catch (e) {
console.error("[Iflytek] ", e);
return NextResponse.json(prettyObject(e));
}
}
async function request(req: NextRequest) {
const controller = new AbortController();
// iflytek use base url or just remove the path
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Iflytek, "");
let baseUrl = serverConfig.iflytekUrl || IFLYTEK_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = `${baseUrl}${path}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
Authorization: req.headers.get("Authorization") ?? "",
},
method: req.method,
body: req.body,
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
// try to refuse some request to some models
if (serverConfig.customModels && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.Iflytek as string,
)
) {
return NextResponse.json(
{
error: true,
message: `you are not allowed to use ${jsonBody?.model} model`,
},
{
status: 403,
},
);
}
} catch (e) {
console.error(`[Iflytek] filter`, e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -1,130 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import {
Moonshot,
MOONSHOT_BASE_URL,
ApiPath,
ModelProvider,
ServiceProvider,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/app/api/auth";
import { isModelAvailableInServer } from "@/app/utils/model";
import type { RequestPayload } from "@/app/client/platforms/openai";
const serverConfig = getServerSideConfig();
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Moonshot Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const authResult = auth(req, ModelProvider.Moonshot);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
try {
const response = await request(req);
return response;
} catch (e) {
console.error("[Moonshot] ", e);
return NextResponse.json(prettyObject(e));
}
}
async function request(req: NextRequest) {
const controller = new AbortController();
// alibaba use base url or just remove the path
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Moonshot, "");
let baseUrl = serverConfig.moonshotUrl || MOONSHOT_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Proxy] ", path);
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = `${baseUrl}${path}`;
const fetchOptions: RequestInit = {
headers: {
"Content-Type": "application/json",
Authorization: req.headers.get("Authorization") ?? "",
},
method: req.method,
body: req.body,
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
// #1815 try to refuse some request to some models
if (serverConfig.customModels && req.body) {
try {
const clonedBody = await req.text();
fetchOptions.body = clonedBody;
const jsonBody = JSON.parse(clonedBody) as { model?: string };
// not undefined and is false
if (
isModelAvailableInServer(
serverConfig.customModels,
jsonBody?.model as string,
ServiceProvider.Moonshot as string,
)
) {
return NextResponse.json(
{
error: true,
message: `you are not allowed to use ${jsonBody?.model} model`,
},
{
status: 403,
},
);
}
} catch (e) {
console.error(`[Moonshot] filter`, e);
}
}
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -3,8 +3,8 @@ import { getServerSideConfig } from "@/app/config/server";
import { ModelProvider, OpenaiPath } from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "./auth";
import { requestOpenai } from "./common";
import { auth } from "../../auth";
import { requestOpenai } from "../../common";
const ALLOWD_PATH = new Set(Object.values(OpenaiPath));
@@ -13,16 +13,14 @@ function getModels(remoteModelRes: OpenAIListModelResponse) {
if (config.disableGPT4) {
remoteModelRes.data = remoteModelRes.data.filter(
(m) =>
!(m.id.startsWith("gpt-4") || m.id.startsWith("chatgpt-4o")) ||
m.id.startsWith("gpt-4o-mini"),
(m) => !m.id.startsWith("gpt-4"),
);
}
return remoteModelRes;
}
export async function handle(
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
@@ -72,3 +70,27 @@ export async function handle(
return NextResponse.json(prettyObject(e));
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
export const preferredRegion = [
"arn1",
"bom1",
"cdg1",
"cle1",
"cpt1",
"dub1",
"fra1",
"gru1",
"hnd1",
"iad1",
"icn1",
"kix1",
"lhr1",
"pdx1",
"sfo1",
"sin1",
"syd1",
];

View File

@@ -1,75 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Proxy Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
// remove path params from searchParams
req.nextUrl.searchParams.delete("path");
req.nextUrl.searchParams.delete("provider");
const subpath = params.path.join("/");
const fetchUrl = `${req.headers.get(
"x-base-url",
)}/${subpath}?${req.nextUrl.searchParams.toString()}`;
const skipHeaders = ["connection", "host", "origin", "referer", "cookie"];
const headers = new Headers(
Array.from(req.headers.entries()).filter((item) => {
if (
item[0].indexOf("x-") > -1 ||
item[0].indexOf("sec-") > -1 ||
skipHeaders.includes(item[0])
) {
return false;
}
return true;
}),
);
const controller = new AbortController();
const fetchOptions: RequestInit = {
headers,
method: req.method,
body: req.body,
// to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
// The latest version of the OpenAI API forced the content-encoding to be "br" in json response
// So if the streaming is disabled, we need to remove the content-encoding header
// Because Vercel uses gzip to compress the response, if we don't remove the content-encoding header
// The browser will try to decode the response with brotli and fail
newHeaders.delete("content-encoding");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -1,99 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { getServerSideConfig } from "@/app/config/server";
import { ModelProvider, STABILITY_BASE_URL } from "@/app/constant";
import { auth } from "@/app/api/auth";
export async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Stability] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const controller = new AbortController();
const serverConfig = getServerSideConfig();
let baseUrl = serverConfig.stabilityUrl || STABILITY_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
let path = `${req.nextUrl.pathname}`.replaceAll("/api/stability/", "");
console.log("[Stability Proxy] ", path);
console.log("[Stability Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const authResult = auth(req, ModelProvider.Stability);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
const bearToken = req.headers.get("Authorization") ?? "";
const token = bearToken.trim().replaceAll("Bearer ", "").trim();
const key = token ? token : serverConfig.stabilityApiKey;
if (!key) {
return NextResponse.json(
{
error: true,
message: `missing STABILITY_API_KEY in server env vars`,
},
{
status: 401,
},
);
}
const fetchUrl = `${baseUrl}/${path}`;
console.log("[Stability Url] ", fetchUrl);
const fetchOptions: RequestInit = {
headers: {
"Content-Type": req.headers.get("Content-Type") || "multipart/form-data",
Accept: req.headers.get("Accept") || "application/json",
Authorization: `Bearer ${key}`,
},
method: req.method,
body: req.body,
// to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -1,124 +0,0 @@
import { getServerSideConfig } from "@/app/config/server";
import {
TENCENT_BASE_URL,
ApiPath,
ModelProvider,
ServiceProvider,
Tencent,
} from "@/app/constant";
import { prettyObject } from "@/app/utils/format";
import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/app/api/auth";
import { isModelAvailableInServer } from "@/app/utils/model";
import { getHeader } from "@/app/utils/tencent";
const serverConfig = getServerSideConfig();
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
) {
console.log("[Tencent Route] params ", params);
if (req.method === "OPTIONS") {
return NextResponse.json({ body: "OK" }, { status: 200 });
}
const authResult = auth(req, ModelProvider.Hunyuan);
if (authResult.error) {
return NextResponse.json(authResult, {
status: 401,
});
}
try {
const response = await request(req);
return response;
} catch (e) {
console.error("[Tencent] ", e);
return NextResponse.json(prettyObject(e));
}
}
export const GET = handle;
export const POST = handle;
export const runtime = "edge";
export const preferredRegion = [
"arn1",
"bom1",
"cdg1",
"cle1",
"cpt1",
"dub1",
"fra1",
"gru1",
"hnd1",
"iad1",
"icn1",
"kix1",
"lhr1",
"pdx1",
"sfo1",
"sin1",
"syd1",
];
async function request(req: NextRequest) {
const controller = new AbortController();
let baseUrl = serverConfig.tencentUrl || TENCENT_BASE_URL;
if (!baseUrl.startsWith("http")) {
baseUrl = `https://${baseUrl}`;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, -1);
}
console.log("[Base Url]", baseUrl);
const timeoutId = setTimeout(
() => {
controller.abort();
},
10 * 60 * 1000,
);
const fetchUrl = baseUrl;
const body = await req.text();
const headers = await getHeader(
body,
serverConfig.tencentSecretId as string,
serverConfig.tencentSecretKey as string,
);
const fetchOptions: RequestInit = {
headers,
method: req.method,
body,
redirect: "manual",
// @ts-ignore
duplex: "half",
signal: controller.signal,
};
try {
const res = await fetch(fetchUrl, fetchOptions);
// to prevent browser prompt for credentials
const newHeaders = new Headers(res.headers);
newHeaders.delete("www-authenticate");
// to disable nginx buffering
newHeaders.set("X-Accel-Buffering", "no");
return new Response(res.body, {
status: res.status,
statusText: res.statusText,
headers: newHeaders,
});
} finally {
clearTimeout(timeoutId);
}
}

View File

@@ -9,14 +9,6 @@ const mergedAllowedWebDavEndpoints = [
...config.allowedWebDevEndpoints,
].filter((domain) => Boolean(domain.trim()));
const normalizeUrl = (url: string) => {
try {
return new URL(url);
} catch (err) {
return null;
}
};
async function handle(
req: NextRequest,
{ params }: { params: { path: string[] } },
@@ -29,23 +21,12 @@ async function handle(
const requestUrl = new URL(req.url);
let endpoint = requestUrl.searchParams.get("endpoint");
let proxy_method = requestUrl.searchParams.get("proxy_method") || req.method;
// Validate the endpoint to prevent potential SSRF attacks
if (
!endpoint ||
!mergedAllowedWebDavEndpoints.some((allowedEndpoint) => {
const normalizedAllowedEndpoint = normalizeUrl(allowedEndpoint);
const normalizedEndpoint = normalizeUrl(endpoint as string);
return (
normalizedEndpoint &&
normalizedEndpoint.hostname === normalizedAllowedEndpoint?.hostname &&
normalizedEndpoint.pathname.startsWith(
normalizedAllowedEndpoint.pathname,
)
);
})
!mergedAllowedWebDavEndpoints.some(
(allowedEndpoint) => endpoint?.startsWith(allowedEndpoint),
)
) {
return NextResponse.json(
{
@@ -66,11 +47,7 @@ async function handle(
const targetPath = `${endpoint}${endpointPath}`;
// only allow MKCOL, GET, PUT
if (
proxy_method !== "MKCOL" &&
proxy_method !== "GET" &&
proxy_method !== "PUT"
) {
if (req.method !== "MKCOL" && req.method !== "GET" && req.method !== "PUT") {
return NextResponse.json(
{
error: true,
@@ -83,7 +60,7 @@ async function handle(
}
// for MKCOL request, only allow request ${folder}
if (proxy_method === "MKCOL" && !targetPath.endsWith(folder)) {
if (req.method === "MKCOL" && !targetPath.endsWith(folder)) {
return NextResponse.json(
{
error: true,
@@ -96,7 +73,7 @@ async function handle(
}
// for GET request, only allow request ending with fileName
if (proxy_method === "GET" && !targetPath.endsWith(fileName)) {
if (req.method === "GET" && !targetPath.endsWith(fileName)) {
return NextResponse.json(
{
error: true,
@@ -109,7 +86,7 @@ async function handle(
}
// for PUT request, only allow request ending with fileName
if (proxy_method === "PUT" && !targetPath.endsWith(fileName)) {
if (req.method === "PUT" && !targetPath.endsWith(fileName)) {
return NextResponse.json(
{
error: true,
@@ -123,7 +100,7 @@ async function handle(
const targetUrl = targetPath;
const method = proxy_method || req.method;
const method = req.method;
const shouldNotHaveBody = ["get", "head"].includes(
method?.toLowerCase() ?? "",
);
@@ -148,7 +125,7 @@ async function handle(
"[Any Proxy]",
targetUrl,
{
method: method,
method: req.method,
},
{
status: fetchResult?.status,

9
app/azure.ts Normal file
View File

@@ -0,0 +1,9 @@
export function makeAzurePath(path: string, apiVersion: string) {
// should omit /v1 prefix
path = path.replaceAll("v1/", "");
// should add api-key to query string
path += `${path.includes("?") ? "&" : "?"}api-version=${apiVersion}`;
return path;
}

View File

@@ -5,23 +5,10 @@ import {
ModelProvider,
ServiceProvider,
} from "../constant";
import {
ChatMessageTool,
ChatMessage,
ModelType,
useAccessStore,
useChatStore,
} from "../store";
import { ChatGPTApi, DalleRequestPayload } from "./platforms/openai";
import { ChatMessage, ModelType, useAccessStore, useChatStore } from "../store";
import { ChatGPTApi } from "./platforms/openai";
import { GeminiProApi } from "./platforms/google";
import { ClaudeApi } from "./platforms/anthropic";
import { ErnieApi } from "./platforms/baidu";
import { DoubaoApi } from "./platforms/bytedance";
import { QwenApi } from "./platforms/alibaba";
import { HunyuanApi } from "./platforms/tencent";
import { MoonshotApi } from "./platforms/moonshot";
import { SparkApi } from "./platforms/iflytek";
export const ROLES = ["system", "user", "assistant"] as const;
export type MessageRole = (typeof ROLES)[number];
@@ -43,15 +30,11 @@ export interface RequestMessage {
export interface LLMConfig {
model: string;
providerName?: string;
temperature?: number;
top_p?: number;
stream?: boolean;
presence_penalty?: number;
frequency_penalty?: number;
size?: DalleRequestPayload["size"];
quality?: DalleRequestPayload["quality"];
style?: DalleRequestPayload["style"];
}
export interface ChatOptions {
@@ -62,8 +45,6 @@ export interface ChatOptions {
onFinish: (message: string) => void;
onError?: (err: Error) => void;
onController?: (controller: AbortController) => void;
onBeforeTool?: (tool: ChatMessageTool) => void;
onAfterTool?: (tool: ChatMessageTool) => void;
}
export interface LLMUsage {
@@ -73,17 +54,14 @@ export interface LLMUsage {
export interface LLMModel {
name: string;
displayName?: string;
available: boolean;
provider: LLMModelProvider;
sorted: number;
}
export interface LLMModelProvider {
id: string;
providerName: string;
providerType: string;
sorted: number;
}
export abstract class LLMApi {
@@ -92,7 +70,7 @@ export abstract class LLMApi {
abstract models(): Promise<LLMModel[]>;
}
type ProviderName = "openai" | "azure" | "claude" | "palm";
type ProviderName = "openai" | "azure" | "claude" | "palm" | "deepseek";
interface Model {
name: string;
@@ -124,24 +102,6 @@ export class ClientApi {
case ModelProvider.Claude:
this.llm = new ClaudeApi();
break;
case ModelProvider.Ernie:
this.llm = new ErnieApi();
break;
case ModelProvider.Doubao:
this.llm = new DoubaoApi();
break;
case ModelProvider.Qwen:
this.llm = new QwenApi();
break;
case ModelProvider.Hunyuan:
this.llm = new HunyuanApi();
break;
case ModelProvider.Moonshot:
this.llm = new MoonshotApi();
break;
case ModelProvider.Iflytek:
this.llm = new SparkApi();
break;
default:
this.llm = new ChatGPTApi();
}
@@ -193,122 +153,40 @@ export class ClientApi {
}
}
export function getBearerToken(
apiKey: string,
noBearer: boolean = false,
): string {
return validString(apiKey)
? `${noBearer ? "" : "Bearer "}${apiKey.trim()}`
: "";
}
export function validString(x: string): boolean {
return x?.length > 0;
}
export function getHeaders() {
const accessStore = useAccessStore.getState();
const chatStore = useChatStore.getState();
const headers: Record<string, string> = {
"Content-Type": "application/json",
Accept: "application/json",
};
const modelConfig = useChatStore.getState().currentSession().mask.modelConfig;
const isGoogle = modelConfig.model.startsWith("gemini");
const isAzure = accessStore.provider === ServiceProvider.Azure;
const isDeepSeek = accessStore.provider === ServiceProvider.DeepSeek;
const authHeader = isAzure ? "api-key" : "Authorization";
const apiKey = isGoogle
? accessStore.googleApiKey
: isAzure
? accessStore.azureApiKey
: accessStore.openaiApiKey;
const clientConfig = getClientConfig();
const makeBearer = (s: string) => `${isAzure ? "" : "Bearer "}${s.trim()}`;
const validString = (x: string) => x && x.length > 0;
function getConfig() {
const modelConfig = chatStore.currentSession().mask.modelConfig;
const isGoogle = modelConfig.providerName == ServiceProvider.Google;
const isAzure = modelConfig.providerName === ServiceProvider.Azure;
const isAnthropic = modelConfig.providerName === ServiceProvider.Anthropic;
const isBaidu = modelConfig.providerName == ServiceProvider.Baidu;
const isByteDance = modelConfig.providerName === ServiceProvider.ByteDance;
const isAlibaba = modelConfig.providerName === ServiceProvider.Alibaba;
const isMoonshot = modelConfig.providerName === ServiceProvider.Moonshot;
const isIflytek = modelConfig.providerName === ServiceProvider.Iflytek;
const isEnabledAccessControl = accessStore.enabledAccessControl();
const apiKey = isGoogle
? accessStore.googleApiKey
: isAzure
? accessStore.azureApiKey
: isAnthropic
? accessStore.anthropicApiKey
: isByteDance
? accessStore.bytedanceApiKey
: isAlibaba
? accessStore.alibabaApiKey
: isMoonshot
? accessStore.moonshotApiKey
: isIflytek
? accessStore.iflytekApiKey && accessStore.iflytekApiSecret
? accessStore.iflytekApiKey + ":" + accessStore.iflytekApiSecret
: ""
: accessStore.openaiApiKey;
return {
isGoogle,
isAzure,
isAnthropic,
isBaidu,
isByteDance,
isAlibaba,
isMoonshot,
isIflytek,
apiKey,
isEnabledAccessControl,
};
}
function getAuthHeader(): string {
return isAzure ? "api-key" : isAnthropic ? "x-api-key" : "Authorization";
}
const {
isGoogle,
isAzure,
isAnthropic,
isBaidu,
apiKey,
isEnabledAccessControl,
} = getConfig();
// when using google api in app, not set auth header
if (isGoogle && clientConfig?.isApp) return headers;
// when using baidu api in app, not set auth header
if (isBaidu && clientConfig?.isApp) return headers;
const authHeader = getAuthHeader();
const bearerToken = getBearerToken(apiKey, isAzure || isAnthropic);
if (bearerToken) {
headers[authHeader] = bearerToken;
} else if (isEnabledAccessControl && validString(accessStore.accessCode)) {
headers["Authorization"] = getBearerToken(
ACCESS_CODE_PREFIX + accessStore.accessCode,
);
if (!(isGoogle && clientConfig?.isApp)) {
// use user's api key first
if (validString(apiKey)) {
headers[authHeader] = makeBearer(apiKey);
} else if (
accessStore.enabledAccessControl() &&
validString(accessStore.accessCode)
) {
headers[authHeader] = makeBearer(
ACCESS_CODE_PREFIX + accessStore.accessCode,
);
}
}
return headers;
}
export function getClientApi(provider: ServiceProvider): ClientApi {
switch (provider) {
case ServiceProvider.Google:
return new ClientApi(ModelProvider.GeminiPro);
case ServiceProvider.Anthropic:
return new ClientApi(ModelProvider.Claude);
case ServiceProvider.Baidu:
return new ClientApi(ModelProvider.Ernie);
case ServiceProvider.ByteDance:
return new ClientApi(ModelProvider.Doubao);
case ServiceProvider.Alibaba:
return new ClientApi(ModelProvider.Qwen);
case ServiceProvider.Tencent:
return new ClientApi(ModelProvider.Hunyuan);
case ServiceProvider.Moonshot:
return new ClientApi(ModelProvider.Moonshot);
case ServiceProvider.Iflytek:
return new ClientApi(ModelProvider.Iflytek);
default:
return new ClientApi(ModelProvider.GPT);
}
}

View File

@@ -1,268 +0,0 @@
"use client";
import {
ApiPath,
Alibaba,
ALIBABA_BASE_URL,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils";
export interface OpenAIListModelResponse {
object: string;
data: Array<{
id: string;
object: string;
root: string;
}>;
}
interface RequestInput {
messages: {
role: "system" | "user" | "assistant";
content: string | MultimodalContent[];
}[];
}
interface RequestParam {
result_format: string;
incremental_output?: boolean;
temperature: number;
repetition_penalty?: number;
top_p: number;
max_tokens?: number;
}
interface RequestPayload {
model: string;
input: RequestInput;
parameters: RequestParam;
}
export class QwenApi implements LLMApi {
path(path: string): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.alibabaUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
baseUrl = isApp ? ALIBABA_BASE_URL : ApiPath.Alibaba;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Alibaba)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
return [baseUrl, path].join("/");
}
extractMessage(res: any) {
return res?.output?.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const messages = options.messages.map((v) => ({
role: v.role,
content: getMessageTextContent(v),
}));
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
},
};
const shouldStream = !!options.config.stream;
const requestPayload: RequestPayload = {
model: modelConfig.model,
input: {
messages,
},
parameters: {
result_format: "message",
incremental_output: shouldStream,
temperature: modelConfig.temperature,
// max_tokens: modelConfig.max_tokens,
top_p: modelConfig.top_p === 1 ? 0.99 : modelConfig.top_p, // qwen top_p is should be < 1
},
};
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path(Alibaba.ChatPath);
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: {
...getHeaders(),
"X-DashScope-SSE": shouldStream ? "enable" : "disable",
},
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
}
// start animaion
animateResponseText();
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
};
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[Alibaba] request response content type: ",
contentType,
);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const choices = json.output.choices as Array<{
message: { content: string };
}>;
const delta = choices[0]?.message?.content;
if (delta) {
remainText += delta;
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
async usage() {
return {
used: 0,
total: 0,
};
}
async models(): Promise<LLMModel[]> {
return [];
}
}
export { Alibaba };

View File

@@ -1,14 +1,9 @@
import { ACCESS_CODE_PREFIX, Anthropic, ApiPath } from "@/app/constant";
import { ChatOptions, getHeaders, LLMApi, MultimodalContent } from "../api";
import {
useAccessStore,
useAppConfig,
useChatStore,
usePluginStore,
ChatMessageTool,
} from "@/app/store";
import { ChatOptions, LLMApi, MultimodalContent } from "../api";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { getClientConfig } from "@/app/config/client";
import { DEFAULT_API_HOST } from "@/app/constant";
import { RequestMessage } from "@/app/typing";
import {
EventStreamContentType,
fetchEventSource,
@@ -17,9 +12,6 @@ import {
import Locale from "../../locales";
import { prettyObject } from "@/app/utils/format";
import { getMessageTextContent, isVisionModel } from "@/app/utils";
import { preProcessImageContent, stream } from "@/app/utils/chat";
import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
import { RequestPayload } from "./openai";
export type MultiBlockContent = {
type: "image" | "text";
@@ -100,12 +92,7 @@ export class ClaudeApi implements LLMApi {
},
};
// try get base64image from local cache image_url
const messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = await preProcessImageContent(v.content);
messages.push({ role: v.role, content });
}
const messages = [...options.messages];
const keys = ["system", "user"];
@@ -198,126 +185,113 @@ export class ClaudeApi implements LLMApi {
const controller = new AbortController();
options.onController?.(controller);
const payload = {
method: "POST",
body: JSON.stringify(requestBody),
signal: controller.signal,
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"x-api-key": accessStore.anthropicApiKey,
"anthropic-version": accessStore.anthropicApiVersion,
Authorization: getAuthKey(accessStore.anthropicApiKey),
},
};
if (shouldStream) {
let index = -1;
const [tools, funcs] = usePluginStore
.getState()
.getAsTools(
useChatStore.getState().currentSession().mask?.plugin || [],
);
return stream(
path,
requestBody,
{
...getHeaders(),
"anthropic-version": accessStore.anthropicApiVersion,
},
// @ts-ignore
tools.map((tool) => ({
name: tool?.function?.name,
description: tool?.function?.description,
input_schema: tool?.function?.parameters,
})),
funcs,
controller,
// parseSSE
(text: string, runTools: ChatMessageTool[]) => {
// console.log("parseSSE", text, runTools);
let chunkJson:
| undefined
| {
type: "content_block_delta" | "content_block_stop";
content_block?: {
type: "tool_use";
id: string;
name: string;
};
delta?: {
type: "text_delta" | "input_json_delta";
text?: string;
partial_json?: string;
};
index: number;
};
chunkJson = JSON.parse(text);
try {
const context = {
text: "",
finished: false,
};
if (chunkJson?.content_block?.type == "tool_use") {
index += 1;
const id = chunkJson?.content_block.id;
const name = chunkJson?.content_block.name;
runTools.push({
id,
type: "function",
function: {
name,
arguments: "",
},
});
const finish = () => {
if (!context.finished) {
options.onFinish(context.text);
context.finished = true;
}
if (
chunkJson?.delta?.type == "input_json_delta" &&
chunkJson?.delta?.partial_json
) {
// @ts-ignore
runTools[index]["function"]["arguments"] +=
chunkJson?.delta?.partial_json;
}
return chunkJson?.delta?.text;
},
// processToolMessage, include tool_calls message and tool call results
(
requestPayload: RequestPayload,
toolCallMessage: any,
toolCallResult: any[],
) => {
// reset index value
index = -1;
// @ts-ignore
requestPayload?.messages?.splice(
// @ts-ignore
requestPayload?.messages?.length,
0,
{
role: "assistant",
content: toolCallMessage.tool_calls.map(
(tool: ChatMessageTool) => ({
type: "tool_use",
id: tool.id,
name: tool?.function?.name,
input: tool?.function?.arguments
? JSON.parse(tool?.function?.arguments)
: {},
}),
),
},
// @ts-ignore
...toolCallResult.map((result) => ({
role: "user",
content: [
{
type: "tool_result",
tool_use_id: result.tool_call_id,
content: result.content,
},
],
})),
);
},
options,
);
};
controller.signal.onabort = finish;
fetchEventSource(path, {
...payload,
async onopen(res) {
const contentType = res.headers.get("content-type");
console.log("response content type: ", contentType);
if (contentType?.startsWith("text/plain")) {
context.text = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [context.text];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
context.text = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
let chunkJson:
| undefined
| {
type: "content_block_delta" | "content_block_stop";
delta?: {
type: "text_delta";
text: string;
};
index: number;
};
try {
chunkJson = JSON.parse(msg.data);
} catch (e) {
console.error("[Response] parse error", msg.data);
}
if (!chunkJson || chunkJson.type === "content_block_stop") {
return finish();
}
const { delta } = chunkJson;
if (delta?.text) {
context.text += delta.text;
options.onUpdate?.(context.text, delta.text);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} catch (e) {
console.error("failed to chat", e);
options.onError?.(e as Error);
}
} else {
const payload = {
method: "POST",
body: JSON.stringify(requestBody),
signal: controller.signal,
headers: {
...getHeaders(), // get common headers
"anthropic-version": accessStore.anthropicApiVersion,
// do not send `anthropicApiKey` in browser!!!
// Authorization: getAuthKey(accessStore.anthropicApiKey),
},
};
try {
controller.signal.onabort = () => options.onFinish("");
@@ -402,8 +376,7 @@ export class ClaudeApi implements LLMApi {
baseUrl = trimEnd(baseUrl, "/");
// try rebuild url, when using cloudflare ai gateway in client
return cloudflareAIGatewayUrl(`${baseUrl}/${path}`);
return `${baseUrl}/${path}`;
}
}
@@ -416,3 +389,27 @@ function trimEnd(s: string, end = " ") {
return s;
}
function bearer(value: string) {
return `Bearer ${value.trim()}`;
}
function getAuthKey(apiKey = "") {
const accessStore = useAccessStore.getState();
const isApp = !!getClientConfig()?.isApp;
let authKey = "";
if (apiKey) {
// use user's api key first
authKey = bearer(apiKey);
} else if (
accessStore.enabledAccessControl() &&
!isApp &&
!!accessStore.accessCode
) {
// or use access code
authKey = bearer(ACCESS_CODE_PREFIX + accessStore.accessCode);
}
return authKey;
}

View File

@@ -1,281 +0,0 @@
"use client";
import {
ApiPath,
Baidu,
BAIDU_BASE_URL,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { getAccessToken } from "@/app/utils/baidu";
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils";
export interface OpenAIListModelResponse {
object: string;
data: Array<{
id: string;
object: string;
root: string;
}>;
}
interface RequestPayload {
messages: {
role: "system" | "user" | "assistant";
content: string | MultimodalContent[];
}[];
stream?: boolean;
model: string;
temperature: number;
presence_penalty: number;
frequency_penalty: number;
top_p: number;
max_tokens?: number;
}
export class ErnieApi implements LLMApi {
path(path: string): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.baiduUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
// do not use proxy for baidubce api
baseUrl = isApp ? BAIDU_BASE_URL : ApiPath.Baidu;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Baidu)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
return [baseUrl, path].join("/");
}
async chat(options: ChatOptions) {
const messages = options.messages.map((v) => ({
// "error_code": 336006, "error_msg": "the role of message with even index in the messages must be user or function",
role: v.role === "system" ? "user" : v.role,
content: getMessageTextContent(v),
}));
// "error_code": 336006, "error_msg": "the length of messages must be an odd number",
if (messages.length % 2 === 0) {
if (messages.at(0)?.role === "user") {
messages.splice(1, 0, {
role: "assistant",
content: " ",
});
} else {
messages.unshift({
role: "user",
content: " ",
});
}
}
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
},
};
const shouldStream = !!options.config.stream;
const requestPayload: RequestPayload = {
messages,
stream: shouldStream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
top_p: modelConfig.top_p,
};
console.log("[Request] Baidu payload: ", requestPayload);
const controller = new AbortController();
options.onController?.(controller);
try {
let chatPath = this.path(Baidu.ChatPath(modelConfig.model));
// getAccessToken can not run in browser, because cors error
if (!!getClientConfig()?.isApp) {
const accessStore = useAccessStore.getState();
if (accessStore.useCustomConfig) {
if (accessStore.isValidBaidu()) {
const { access_token } = await getAccessToken(
accessStore.baiduApiKey,
accessStore.baiduSecretKey,
);
chatPath = `${chatPath}${
chatPath.includes("?") ? "&" : "?"
}access_token=${access_token}`;
}
}
}
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
}
// start animaion
animateResponseText();
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
};
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log("[Baidu] request response content type: ", contentType);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const delta = json?.result;
if (delta) {
remainText += delta;
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
const message = resJson?.result;
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
async usage() {
return {
used: 0,
total: 0,
};
}
async models(): Promise<LLMModel[]> {
return [];
}
}
export { Baidu };

View File

@@ -1,255 +0,0 @@
"use client";
import {
ApiPath,
ByteDance,
BYTEDANCE_BASE_URL,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils";
export interface OpenAIListModelResponse {
object: string;
data: Array<{
id: string;
object: string;
root: string;
}>;
}
interface RequestPayload {
messages: {
role: "system" | "user" | "assistant";
content: string | MultimodalContent[];
}[];
stream?: boolean;
model: string;
temperature: number;
presence_penalty: number;
frequency_penalty: number;
top_p: number;
max_tokens?: number;
}
export class DoubaoApi implements LLMApi {
path(path: string): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.bytedanceUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
baseUrl = isApp ? BYTEDANCE_BASE_URL : ApiPath.ByteDance;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.ByteDance)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
return [baseUrl, path].join("/");
}
extractMessage(res: any) {
return res.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const messages = options.messages.map((v) => ({
role: v.role,
content: getMessageTextContent(v),
}));
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
},
};
const shouldStream = !!options.config.stream;
const requestPayload: RequestPayload = {
messages,
stream: shouldStream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
top_p: modelConfig.top_p,
};
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path(ByteDance.ChatPath);
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
}
// start animaion
animateResponseText();
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
};
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[ByteDance] request response content type: ",
contentType,
);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const choices = json.choices as Array<{
delta: { content: string };
}>;
const delta = choices[0]?.delta?.content;
if (delta) {
remainText += delta;
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
async usage() {
return {
used: 0,
total: 0,
};
}
async models(): Promise<LLMModel[]> {
return [];
}
}
export { ByteDance };

View File

@@ -1,52 +1,15 @@
import { ApiPath, Google, REQUEST_TIMEOUT_MS } from "@/app/constant";
import { Google, REQUEST_TIMEOUT_MS } from "@/app/constant";
import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { getClientConfig } from "@/app/config/client";
import { DEFAULT_API_HOST } from "@/app/constant";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import {
getMessageTextContent,
getMessageImages,
isVisionModel,
} from "@/app/utils";
import { preProcessImageContent } from "@/app/utils/chat";
export class GeminiProApi implements LLMApi {
path(path: string): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.googleUrl;
}
const isApp = !!getClientConfig()?.isApp;
if (baseUrl.length === 0) {
baseUrl = isApp ? DEFAULT_API_HOST + `/api/proxy/google` : ApiPath.Google;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Google)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
let chatPath = [baseUrl, path].join("/");
chatPath += chatPath.includes("?") ? "&alt=sse" : "?alt=sse";
// if chatPath.startsWith('http') then add key in query string
if (chatPath.startsWith("http") && accessStore.googleApiKey) {
chatPath += `&key=${accessStore.googleApiKey}`;
}
return chatPath;
}
extractMessage(res: any) {
console.log("[Response] gemini-pro response: ", res);
@@ -57,16 +20,9 @@ export class GeminiProApi implements LLMApi {
);
}
async chat(options: ChatOptions): Promise<void> {
const apiClient = this;
// const apiClient = this;
let multimodal = false;
// try get base64image from local cache image_url
const _messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = await preProcessImageContent(v.content);
_messages.push({ role: v.role, content });
}
const messages = _messages.map((v) => {
const messages = options.messages.map((v) => {
let parts: any[] = [{ text: getMessageTextContent(v) }];
if (isVisionModel(options.config.model)) {
const images = getMessageImages(v);
@@ -108,9 +64,6 @@ export class GeminiProApi implements LLMApi {
// if (visionModel && messages.length > 1) {
// options.onError?.(new Error("Multiturn chat is not enabled for models/gemini-pro-vision"));
// }
const accessStore = useAccessStore.getState();
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
@@ -132,30 +85,48 @@ export class GeminiProApi implements LLMApi {
safetySettings: [
{
category: "HARM_CATEGORY_HARASSMENT",
threshold: accessStore.googleSafetySettings,
threshold: "BLOCK_ONLY_HIGH",
},
{
category: "HARM_CATEGORY_HATE_SPEECH",
threshold: accessStore.googleSafetySettings,
threshold: "BLOCK_ONLY_HIGH",
},
{
category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
threshold: accessStore.googleSafetySettings,
threshold: "BLOCK_ONLY_HIGH",
},
{
category: "HARM_CATEGORY_DANGEROUS_CONTENT",
threshold: accessStore.googleSafetySettings,
threshold: "BLOCK_ONLY_HIGH",
},
],
};
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.googleUrl;
}
const isApp = !!getClientConfig()?.isApp;
let shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
// https://github.com/google-gemini/cookbook/blob/main/quickstarts/rest/Streaming_REST.ipynb
const chatPath = this.path(Google.ChatPath(modelConfig.model));
// let baseUrl = accessStore.googleUrl;
if (!baseUrl) {
baseUrl = isApp
? DEFAULT_API_HOST + "/api/proxy/google/" + Google.ChatPath(modelConfig.model)
: this.path(Google.ChatPath(modelConfig.model));
}
if (isApp) {
baseUrl += `?key=${accessStore.googleApiKey}`;
}
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
@@ -168,17 +139,16 @@ export class GeminiProApi implements LLMApi {
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
let existingTexts: string[] = [];
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
finished = true;
options.onFinish(existingTexts.join(""));
};
// animate response to make it looks smooth
@@ -203,83 +173,74 @@ export class GeminiProApi implements LLMApi {
// start animaion
animateResponseText();
controller.signal.onabort = finish;
fetch(
baseUrl.replace("generateContent", "streamGenerateContent"),
chatPayload,
)
.then((response) => {
const reader = response?.body?.getReader();
const decoder = new TextDecoder();
let partialData = "";
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[Gemini] request response content type: ",
contentType,
);
return reader?.read().then(function processText({
done,
value,
}): Promise<any> {
if (done) {
if (response.status !== 200) {
try {
let data = JSON.parse(ensureProperEnding(partialData));
if (data && data[0].error) {
options.onError?.(new Error(data[0].error.message));
} else {
options.onError?.(new Error("Request failed"));
}
} catch (_) {
options.onError?.(new Error("Request failed"));
}
}
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
console.log("Stream complete");
// options.onFinish(responseText + remainText);
finished = true;
return Promise.resolve();
}
partialData += decoder.decode(value, { stream: true });
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
let data = JSON.parse(ensureProperEnding(partialData));
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
const textArray = data.reduce(
(acc: string[], item: { candidates: any[] }) => {
const texts = item.candidates.map((candidate) =>
candidate.content.parts
.map((part: { text: any }) => part.text)
.join(""),
);
return acc.concat(texts);
},
[],
);
if (textArray.length > existingTexts.length) {
const deltaArray = textArray.slice(existingTexts.length);
existingTexts = textArray;
remainText += deltaArray.join("");
}
} catch (error) {
// console.log("[Response Animation] error: ", error,partialData);
// skip error message when parsing json
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const delta = apiClient.extractMessage(json);
if (delta) {
remainText += delta;
}
const blockReason = json?.promptFeedback?.blockReason;
if (blockReason) {
// being blocked
console.log(`[Google] [Safety Ratings] result:`, blockReason);
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
return reader.read().then(processText);
});
})
.catch((error) => {
console.error("Error:", error);
});
} else {
const res = await fetch(chatPath, chatPayload);
const res = await fetch(baseUrl, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
if (resJson?.promptFeedback?.blockReason) {
@@ -291,7 +252,7 @@ export class GeminiProApi implements LLMApi {
),
);
}
const message = apiClient.extractMessage(resJson);
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
@@ -305,4 +266,14 @@ export class GeminiProApi implements LLMApi {
async models(): Promise<LLMModel[]> {
return [];
}
path(path: string): string {
return "/api/google/" + path;
}
}
function ensureProperEnding(str: string) {
if (str.startsWith("[") && !str.endsWith("]")) {
return str + "]";
}
return str;
}

View File

@@ -1,240 +0,0 @@
"use client";
import {
ApiPath,
DEFAULT_API_HOST,
Iflytek,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { ChatOptions, getHeaders, LLMApi, LLMModel } from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils";
import { OpenAIListModelResponse, RequestPayload } from "./openai";
export class SparkApi implements LLMApi {
private disableListModels = true;
path(path: string): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.iflytekUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
const apiPath = ApiPath.Iflytek;
baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Iflytek)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
return [baseUrl, path].join("/");
}
extractMessage(res: any) {
return res.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = getMessageTextContent(v);
messages.push({ role: v.role, content });
}
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
providerName: options.config.providerName,
},
};
const requestPayload: RequestPayload = {
messages,
stream: options.config.stream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
top_p: modelConfig.top_p,
// max_tokens: Math.max(modelConfig.max_tokens, 1024),
// Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
};
console.log("[Request] Spark payload: ", requestPayload);
const shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path(Iflytek.ChatPath);
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
};
// Make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
// Animate response text to make it look smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
}
// Start animation
animateResponseText();
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
};
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log("[Spark] request response content type: ", contentType);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
// Handle different error scenarios
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
extraInfo = Locale.Error.Unauthorized;
}
options.onError?.(
new Error(
`Request failed with status ${res.status}: ${extraInfo}`,
),
);
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const choices = json.choices as Array<{
delta: { content: string };
}>;
const delta = choices[0]?.delta?.content;
if (delta) {
remainText += delta;
}
} catch (e) {
console.error("[Request] parse error", text);
options.onError?.(new Error(`Failed to parse response: ${text}`));
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
if (!res.ok) {
const errorText = await res.text();
options.onError?.(
new Error(`Request failed with status ${res.status}: ${errorText}`),
);
return;
}
const resJson = await res.json();
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
async usage() {
return {
used: 0,
total: 0,
};
}
async models(): Promise<LLMModel[]> {
return [];
}
}

View File

@@ -1,208 +0,0 @@
"use client";
// azure and openai, using same models. so using same LLMApi.
import {
ApiPath,
DEFAULT_API_HOST,
DEFAULT_MODELS,
Moonshot,
REQUEST_TIMEOUT_MS,
ServiceProvider,
} from "@/app/constant";
import {
useAccessStore,
useAppConfig,
useChatStore,
ChatMessageTool,
usePluginStore,
} from "@/app/store";
import { collectModelsWithDefaultModel } from "@/app/utils/model";
import { preProcessImageContent, stream } from "@/app/utils/chat";
import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
LLMUsage,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils";
import { OpenAIListModelResponse, RequestPayload } from "./openai";
export class MoonshotApi implements LLMApi {
private disableListModels = true;
path(path: string): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.moonshotUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
const apiPath = ApiPath.Moonshot;
baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Moonshot)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
return [baseUrl, path].join("/");
}
extractMessage(res: any) {
return res.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = getMessageTextContent(v);
messages.push({ role: v.role, content });
}
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
providerName: options.config.providerName,
},
};
const requestPayload: RequestPayload = {
messages,
stream: options.config.stream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
top_p: modelConfig.top_p,
// max_tokens: Math.max(modelConfig.max_tokens, 1024),
// Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
};
console.log("[Request] openai payload: ", requestPayload);
const shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path(Moonshot.ChatPath);
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
const [tools, funcs] = usePluginStore
.getState()
.getAsTools(
useChatStore.getState().currentSession().mask?.plugin || [],
);
return stream(
chatPath,
requestPayload,
getHeaders(),
tools as any,
funcs,
controller,
// parseSSE
(text: string, runTools: ChatMessageTool[]) => {
// console.log("parseSSE", text, runTools);
const json = JSON.parse(text);
const choices = json.choices as Array<{
delta: {
content: string;
tool_calls: ChatMessageTool[];
};
}>;
const tool_calls = choices[0]?.delta?.tool_calls;
if (tool_calls?.length > 0) {
const index = tool_calls[0]?.index;
const id = tool_calls[0]?.id;
const args = tool_calls[0]?.function?.arguments;
if (id) {
runTools.push({
id,
type: tool_calls[0]?.type,
function: {
name: tool_calls[0]?.function?.name as string,
arguments: args,
},
});
} else {
// @ts-ignore
runTools[index]["function"]["arguments"] += args;
}
}
return choices[0]?.delta?.content;
},
// processToolMessage, include tool_calls message and tool call results
(
requestPayload: RequestPayload,
toolCallMessage: any,
toolCallResult: any[],
) => {
// @ts-ignore
requestPayload?.messages?.splice(
// @ts-ignore
requestPayload?.messages?.length,
0,
toolCallMessage,
...toolCallResult,
);
},
options,
);
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
async usage() {
return {
used: 0,
total: 0,
};
}
async models(): Promise<LLMModel[]> {
return [];
}
}

View File

@@ -1,30 +1,13 @@
"use client";
// azure and openai, using same models. so using same LLMApi.
import {
ApiPath,
DEFAULT_API_HOST,
DEFAULT_MODELS,
OpenaiPath,
Azure,
REQUEST_TIMEOUT_MS,
ServiceProvider,
} from "@/app/constant";
import {
ChatMessageTool,
useAccessStore,
useAppConfig,
useChatStore,
usePluginStore,
} from "@/app/store";
import { collectModelsWithDefaultModel } from "@/app/utils/model";
import {
preProcessImageContent,
uploadImage,
base64Image2Blob,
stream,
} from "@/app/utils/chat";
import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
import { DalleSize, DalleQuality, DalleStyle } from "@/app/typing";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import {
ChatOptions,
@@ -41,11 +24,11 @@ import {
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { makeAzurePath } from "@/app/azure";
import {
getMessageTextContent,
getMessageImages,
isVisionModel,
isDalle3 as _isDalle3,
} from "@/app/utils";
export interface OpenAIListModelResponse {
@@ -57,7 +40,7 @@ export interface OpenAIListModelResponse {
}>;
}
export interface RequestPayload {
interface RequestPayload {
messages: {
role: "system" | "user" | "assistant";
content: string | MultimodalContent[];
@@ -71,16 +54,6 @@ export interface RequestPayload {
max_tokens?: number;
}
export interface DalleRequestPayload {
model: string;
prompt: string;
response_format: "url" | "b64_json";
n: number;
size: DalleSize;
quality: DalleQuality;
style: DalleStyle;
}
export class ChatGPTApi implements LLMApi {
private disableListModels = true;
@@ -89,241 +62,227 @@ export class ChatGPTApi implements LLMApi {
let baseUrl = "";
const isAzure = path.includes("deployments");
if (accessStore.useCustomConfig) {
const isAzure = accessStore.provider === ServiceProvider.Azure;
if (isAzure && !accessStore.isValidAzure()) {
throw Error(
"incomplete azure config, please check it in your settings page",
);
}
if (isAzure) {
path = makeAzurePath(path, accessStore.azureApiVersion);
}
baseUrl = isAzure ? accessStore.azureUrl : accessStore.openaiUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
const apiPath = isAzure ? ApiPath.Azure : ApiPath.OpenAI;
baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
baseUrl = isApp
? DEFAULT_API_HOST + "/proxy" + ApiPath.OpenAI
: ApiPath.OpenAI;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (
!baseUrl.startsWith("http") &&
!isAzure &&
!baseUrl.startsWith(ApiPath.OpenAI)
) {
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.OpenAI)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl, path);
// try rebuild url, when using cloudflare ai gateway in client
return cloudflareAIGatewayUrl([baseUrl, path].join("/"));
return [baseUrl, path].join("/");
}
async extractMessage(res: any) {
if (res.error) {
return "```\n" + JSON.stringify(res, null, 4) + "\n```";
}
// dalle3 model return url, using url create image message
if (res.data) {
let url = res.data?.at(0)?.url ?? "";
const b64_json = res.data?.at(0)?.b64_json ?? "";
if (!url && b64_json) {
// uploadImage
url = await uploadImage(base64Image2Blob(b64_json, "image/png"));
}
return [
{
type: "image_url",
image_url: {
url,
},
},
];
}
return res.choices?.at(0)?.message?.content ?? res;
extractMessage(res: any) {
return res.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const visionModel = isVisionModel(options.config.model);
const messages = options.messages.map((v) => ({
role: v.role,
content: visionModel ? v.content : getMessageTextContent(v),
}));
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
providerName: options.config.providerName,
},
};
let requestPayload: RequestPayload | DalleRequestPayload;
const requestPayload: RequestPayload = {
messages,
stream: options.config.stream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
top_p: modelConfig.top_p,
// max_tokens: Math.max(modelConfig.max_tokens, 1024),
// Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
};
const isDalle3 = _isDalle3(options.config.model);
const isO1 = options.config.model.startsWith("o1");
if (isDalle3) {
const prompt = getMessageTextContent(
options.messages.slice(-1)?.pop() as any,
);
requestPayload = {
model: options.config.model,
prompt,
// URLs are only valid for 60 minutes after the image has been generated.
response_format: "b64_json", // using b64_json, and save image in CacheStorage
n: 1,
size: options.config?.size ?? "1024x1024",
quality: options.config?.quality ?? "standard",
style: options.config?.style ?? "vivid",
};
} else {
const visionModel = isVisionModel(options.config.model);
const messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = visionModel
? await preProcessImageContent(v.content)
: getMessageTextContent(v);
if (!(isO1 && v.role === "system"))
messages.push({ role: v.role, content });
}
// O1 not support image, tools (plugin in ChatGPTNextWeb) and system, stream, logprobs, temperature, top_p, n, presence_penalty, frequency_penalty yet.
requestPayload = {
messages,
stream: !isO1 ? options.config.stream : false,
model: modelConfig.model,
temperature: !isO1 ? modelConfig.temperature : 1,
presence_penalty: !isO1 ? modelConfig.presence_penalty : 0,
frequency_penalty: !isO1 ? modelConfig.frequency_penalty : 0,
top_p: !isO1 ? modelConfig.top_p : 1,
// max_tokens: Math.max(modelConfig.max_tokens, 1024),
// Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
};
// add max_tokens to vision model
if (visionModel) {
requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
}
// add max_tokens to vision model
if (visionModel && modelConfig.model.includes("preview")) {
requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
}
console.log("[Request] openai payload: ", requestPayload);
const shouldStream = !isDalle3 && !!options.config.stream && !isO1;
const shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
let chatPath = "";
if (modelConfig.providerName === ServiceProvider.Azure) {
// find model, and get displayName as deployName
const { models: configModels, customModels: configCustomModels } =
useAppConfig.getState();
const {
defaultModel,
customModels: accessCustomModels,
useCustomConfig,
} = useAccessStore.getState();
const models = collectModelsWithDefaultModel(
configModels,
[configCustomModels, accessCustomModels].join(","),
defaultModel,
);
const model = models.find(
(model) =>
model.name === modelConfig.model &&
model?.provider?.providerName === ServiceProvider.Azure,
);
chatPath = this.path(
(isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
(model?.displayName ?? model?.name) as string,
useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
),
);
} else {
chatPath = this.path(
isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
);
}
const chatPath = this.path(OpenaiPath.ChatPath);
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
const [tools, funcs] = usePluginStore
.getState()
.getAsTools(
useChatStore.getState().currentSession().mask?.plugin || [],
);
// console.log("getAsTools", tools, funcs);
stream(
chatPath,
requestPayload,
getHeaders(),
tools as any,
funcs,
controller,
// parseSSE
(text: string, runTools: ChatMessageTool[]) => {
// console.log("parseSSE", text, runTools);
const json = JSON.parse(text);
const choices = json.choices as Array<{
delta: {
content: string;
tool_calls: ChatMessageTool[];
};
}>;
const tool_calls = choices[0]?.delta?.tool_calls;
if (tool_calls?.length > 0) {
const index = tool_calls[0]?.index;
const id = tool_calls[0]?.id;
const args = tool_calls[0]?.function?.arguments;
if (id) {
runTools.push({
id,
type: tool_calls[0]?.type,
function: {
name: tool_calls[0]?.function?.name as string,
arguments: args,
},
});
} else {
// @ts-ignore
runTools[index]["function"]["arguments"] += args;
}
let responseText = "";
let remainText = "";
let finished = false;
// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return choices[0]?.delta?.content;
},
// processToolMessage, include tool_calls message and tool call results
(
requestPayload: RequestPayload,
toolCallMessage: any,
toolCallResult: any[],
) => {
// @ts-ignore
requestPayload?.messages?.splice(
// @ts-ignore
requestPayload?.messages?.length,
0,
toolCallMessage,
...toolCallResult,
);
},
options,
);
} else {
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
}
// start animaion
animateResponseText();
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
isDalle3 || isO1 ? REQUEST_TIMEOUT_MS * 2 : REQUEST_TIMEOUT_MS, // dalle3 using b64_json is slow.
);
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[OpenAI] request response content type: ",
contentType,
);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const choices = json.choices as Array<{
delta: { content: string };
}>;
const delta = choices[0]?.delta?.content;
const textmoderation = json?.prompt_filter_results;
if (delta) {
remainText += delta;
}
if (
textmoderation &&
textmoderation.length > 0 &&
ServiceProvider.Azure
) {
const contentFilterResults =
textmoderation[0]?.content_filter_results;
console.log(
`[${ServiceProvider.Azure}] [Text Moderation] flagged categories result:`,
contentFilterResults,
);
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
const message = await this.extractMessage(resJson);
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
@@ -410,26 +369,20 @@ export class ChatGPTApi implements LLMApi {
});
const resJson = (await res.json()) as OpenAIListModelResponse;
const chatModels = resJson.data?.filter(
(m) => m.id.startsWith("gpt-") || m.id.startsWith("chatgpt-"),
);
const chatModels = resJson.data?.filter((m) => m.id.startsWith("gpt-"));
console.log("[Models]", chatModels);
if (!chatModels) {
return [];
}
//由于目前 OpenAI 的 disableListModels 默认为 true所以当前实际不会运行到这场
let seq = 1000; //同 Constant.ts 中的排序保持一致
return chatModels.map((m) => ({
name: m.id,
available: true,
sorted: seq++,
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
sorted: 1,
},
}));
}

View File

@@ -1,268 +0,0 @@
"use client";
import { ApiPath, DEFAULT_API_HOST, REQUEST_TIMEOUT_MS } from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
import {
EventStreamContentType,
fetchEventSource,
} from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent, isVisionModel } from "@/app/utils";
import mapKeys from "lodash-es/mapKeys";
import mapValues from "lodash-es/mapValues";
import isArray from "lodash-es/isArray";
import isObject from "lodash-es/isObject";
export interface OpenAIListModelResponse {
object: string;
data: Array<{
id: string;
object: string;
root: string;
}>;
}
interface RequestPayload {
Messages: {
Role: "system" | "user" | "assistant";
Content: string | MultimodalContent[];
}[];
Stream?: boolean;
Model: string;
Temperature: number;
TopP: number;
}
function capitalizeKeys(obj: any): any {
if (isArray(obj)) {
return obj.map(capitalizeKeys);
} else if (isObject(obj)) {
return mapValues(
mapKeys(obj, (value: any, key: string) =>
key.replace(/(^|_)(\w)/g, (m, $1, $2) => $2.toUpperCase()),
),
capitalizeKeys,
);
} else {
return obj;
}
}
export class HunyuanApi implements LLMApi {
path(): string {
const accessStore = useAccessStore.getState();
let baseUrl = "";
if (accessStore.useCustomConfig) {
baseUrl = accessStore.tencentUrl;
}
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
baseUrl = isApp
? DEFAULT_API_HOST + "/api/proxy/tencent"
: ApiPath.Tencent;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Tencent)) {
baseUrl = "https://" + baseUrl;
}
console.log("[Proxy Endpoint] ", baseUrl);
return baseUrl;
}
extractMessage(res: any) {
return res.Choices?.at(0)?.Message?.Content ?? "";
}
async chat(options: ChatOptions) {
const visionModel = isVisionModel(options.config.model);
const messages = options.messages.map((v, index) => ({
// "Messages 中 system 角色必须位于列表的最开始"
role: index !== 0 && v.role === "system" ? "user" : v.role,
content: visionModel ? v.content : getMessageTextContent(v),
}));
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
},
};
const requestPayload: RequestPayload = capitalizeKeys({
model: modelConfig.model,
messages,
temperature: modelConfig.temperature,
top_p: modelConfig.top_p,
stream: options.config.stream,
});
console.log("[Request] Tencent payload: ", requestPayload);
const shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
try {
const chatPath = this.path();
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
};
// make a fetch request
const requestTimeoutId = setTimeout(
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return;
}
if (remainText.length > 0) {
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
const fetchText = remainText.slice(0, fetchCount);
responseText += fetchText;
remainText = remainText.slice(fetchCount);
options.onUpdate?.(responseText, fetchText);
}
requestAnimationFrame(animateResponseText);
}
// start animaion
animateResponseText();
const finish = () => {
if (!finished) {
finished = true;
options.onFinish(responseText + remainText);
}
};
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[Tencent] request response content type: ",
contentType,
);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
if (extraInfo) {
responseTexts.push(extraInfo);
}
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
const text = msg.data;
try {
const json = JSON.parse(text);
const choices = json.Choices as Array<{
Delta: { Content: string };
}>;
const delta = choices[0]?.Delta?.Content;
if (delta) {
remainText += delta;
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
const resJson = await res.json();
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
}
}
async usage() {
return {
used: 0,
total: 0,
};
}
async models(): Promise<LLMModel[]> {
return [];
}
}

View File

@@ -41,16 +41,13 @@ interface ChatCommands {
del?: Command;
}
// Compatible with Chinese colon character ""
export const ChatCommandPrefix = /^[:]/;
export const ChatCommandPrefix = ":";
export function useChatCommand(commands: ChatCommands = {}) {
function extract(userInput: string) {
const match = userInput.match(ChatCommandPrefix);
if (match) {
return userInput.slice(1) as keyof ChatCommands;
}
return userInput as keyof ChatCommands;
return (
userInput.startsWith(ChatCommandPrefix) ? userInput.slice(1) : userInput
) as keyof ChatCommands;
}
function search(userInput: string) {
@@ -60,7 +57,7 @@ export function useChatCommand(commands: ChatCommands = {}) {
.filter((c) => c.startsWith(input))
.map((c) => ({
title: desc[c as keyof ChatCommands],
content: ":" + c,
content: ChatCommandPrefix + c,
}));
}

View File

@@ -1,31 +0,0 @@
.artifacts {
display: flex;
width: 100%;
height: 100%;
flex-direction: column;
&-header {
display: flex;
align-items: center;
height: 36px;
padding: 20px;
background: var(--second);
}
&-title {
flex: 1;
text-align: center;
font-weight: bold;
font-size: 24px;
}
&-content {
flex-grow: 1;
padding: 0 20px 20px 20px;
background-color: var(--second);
}
}
.artifacts-iframe {
width: 100%;
border: var(--border-in-light);
border-radius: 6px;
background-color: var(--gray);
}

View File

@@ -1,267 +0,0 @@
import {
useEffect,
useState,
useRef,
useMemo,
forwardRef,
useImperativeHandle,
} from "react";
import { useParams } from "react-router";
import { useWindowSize } from "@/app/utils";
import { IconButton } from "./button";
import { nanoid } from "nanoid";
import ExportIcon from "../icons/share.svg";
import CopyIcon from "../icons/copy.svg";
import DownloadIcon from "../icons/download.svg";
import GithubIcon from "../icons/github.svg";
import LoadingButtonIcon from "../icons/loading.svg";
import ReloadButtonIcon from "../icons/reload.svg";
import Locale from "../locales";
import { Modal, showToast } from "./ui-lib";
import { copyToClipboard, downloadAs } from "../utils";
import { Path, ApiPath, REPO_URL } from "@/app/constant";
import { Loading } from "./home";
import styles from "./artifacts.module.scss";
type HTMLPreviewProps = {
code: string;
autoHeight?: boolean;
height?: number | string;
onLoad?: (title?: string) => void;
};
export type HTMLPreviewHander = {
reload: () => void;
};
export const HTMLPreview = forwardRef<HTMLPreviewHander, HTMLPreviewProps>(
function HTMLPreview(props, ref) {
const iframeRef = useRef<HTMLIFrameElement>(null);
const [frameId, setFrameId] = useState<string>(nanoid());
const [iframeHeight, setIframeHeight] = useState(600);
const [title, setTitle] = useState("");
/*
* https://stackoverflow.com/questions/19739001/what-is-the-difference-between-srcdoc-and-src-datatext-html-in-an
* 1. using srcdoc
* 2. using src with dataurl:
* easy to share
* length limit (Data URIs cannot be larger than 32,768 characters.)
*/
useEffect(() => {
const handleMessage = (e: any) => {
const { id, height, title } = e.data;
setTitle(title);
if (id == frameId) {
setIframeHeight(height);
}
};
window.addEventListener("message", handleMessage);
return () => {
window.removeEventListener("message", handleMessage);
};
}, [frameId]);
useImperativeHandle(ref, () => ({
reload: () => {
setFrameId(nanoid());
},
}));
const height = useMemo(() => {
if (!props.autoHeight) return props.height || 600;
if (typeof props.height === "string") {
return props.height;
}
const parentHeight = props.height || 600;
return iframeHeight + 40 > parentHeight
? parentHeight
: iframeHeight + 40;
}, [props.autoHeight, props.height, iframeHeight]);
const srcDoc = useMemo(() => {
const script = `<script>window.addEventListener("DOMContentLoaded", () => new ResizeObserver((entries) => parent.postMessage({id: '${frameId}', height: entries[0].target.clientHeight}, '*')).observe(document.body))</script>`;
if (props.code.includes("<!DOCTYPE html>")) {
props.code.replace("<!DOCTYPE html>", "<!DOCTYPE html>" + script);
}
return script + props.code;
}, [props.code, frameId]);
const handleOnLoad = () => {
if (props?.onLoad) {
props.onLoad(title);
}
};
return (
<iframe
className={styles["artifacts-iframe"]}
key={frameId}
ref={iframeRef}
sandbox="allow-forms allow-modals allow-scripts"
style={{ height }}
srcDoc={srcDoc}
onLoad={handleOnLoad}
/>
);
},
);
export function ArtifactsShareButton({
getCode,
id,
style,
fileName,
}: {
getCode: () => string;
id?: string;
style?: any;
fileName?: string;
}) {
const [loading, setLoading] = useState(false);
const [name, setName] = useState(id);
const [show, setShow] = useState(false);
const shareUrl = useMemo(
() => [location.origin, "#", Path.Artifacts, "/", name].join(""),
[name],
);
const upload = (code: string) =>
id
? Promise.resolve({ id })
: fetch(ApiPath.Artifacts, {
method: "POST",
body: code,
})
.then((res) => res.json())
.then(({ id }) => {
if (id) {
return { id };
}
throw Error();
})
.catch((e) => {
showToast(Locale.Export.Artifacts.Error);
});
return (
<>
<div className="window-action-button" style={style}>
<IconButton
icon={loading ? <LoadingButtonIcon /> : <ExportIcon />}
bordered
title={Locale.Export.Artifacts.Title}
onClick={() => {
if (loading) return;
setLoading(true);
upload(getCode())
.then((res) => {
if (res?.id) {
setShow(true);
setName(res?.id);
}
})
.finally(() => setLoading(false));
}}
/>
</div>
{show && (
<div className="modal-mask">
<Modal
title={Locale.Export.Artifacts.Title}
onClose={() => setShow(false)}
actions={[
<IconButton
key="download"
icon={<DownloadIcon />}
bordered
text={Locale.Export.Download}
onClick={() => {
downloadAs(getCode(), `${fileName || name}.html`).then(() =>
setShow(false),
);
}}
/>,
<IconButton
key="copy"
icon={<CopyIcon />}
bordered
text={Locale.Chat.Actions.Copy}
onClick={() => {
copyToClipboard(shareUrl).then(() => setShow(false));
}}
/>,
]}
>
<div>
<a target="_blank" href={shareUrl}>
{shareUrl}
</a>
</div>
</Modal>
</div>
)}
</>
);
}
export function Artifacts() {
const { id } = useParams();
const [code, setCode] = useState("");
const [loading, setLoading] = useState(true);
const [fileName, setFileName] = useState("");
const previewRef = useRef<HTMLPreviewHander>(null);
useEffect(() => {
if (id) {
fetch(`${ApiPath.Artifacts}?id=${id}`)
.then((res) => {
if (res.status > 300) {
throw Error("can not get content");
}
return res;
})
.then((res) => res.text())
.then(setCode)
.catch((e) => {
showToast(Locale.Export.Artifacts.Error);
});
}
}, [id]);
return (
<div className={styles["artifacts"]}>
<div className={styles["artifacts-header"]}>
<a href={REPO_URL} target="_blank" rel="noopener noreferrer">
<IconButton bordered icon={<GithubIcon />} shadow />
</a>
<IconButton
bordered
style={{ marginLeft: 20 }}
icon={<ReloadButtonIcon />}
shadow
onClick={() => previewRef.current?.reload()}
/>
<div className={styles["artifacts-title"]}>NextChat Artifacts</div>
<ArtifactsShareButton
id={id}
getCode={() => code}
fileName={fileName}
/>
</div>
<div className={styles["artifacts-content"]}>
{loading && <Loading />}
{code && (
<HTMLPreview
code={code}
ref={previewRef}
autoHeight={false}
height={"100%"}
onLoad={(title) => {
setFileName(title as string);
setLoading(false);
}}
/>
)}
</div>
</div>
);
}

View File

@@ -1,7 +1,6 @@
import * as React from "react";
import styles from "./button.module.scss";
import { CSSProperties } from "react";
export type ButtonType = "primary" | "danger" | null;
@@ -17,8 +16,6 @@ export function IconButton(props: {
disabled?: boolean;
tabIndex?: number;
autoFocus?: boolean;
style?: CSSProperties;
aria?: string;
}) {
return (
<button
@@ -34,12 +31,9 @@ export function IconButton(props: {
role="button"
tabIndex={props.tabIndex}
autoFocus={props.autoFocus}
style={props.style}
aria-label={props.aria}
>
{props.icon && (
<div
aria-label={props.text || props.title}
className={
styles["icon-button-icon"] +
` ${props.type === "primary" && "no-dark"}`
@@ -50,12 +44,7 @@ export function IconButton(props: {
)}
{props.text && (
<div
aria-label={props.text || props.title}
className={styles["icon-button-text"]}
>
{props.text}
</div>
<div className={styles["icon-button-text"]}>{props.text}</div>
)}
</button>
);

View File

@@ -346,12 +346,6 @@
flex-wrap: nowrap;
}
}
.chat-model-name {
font-size: 12px;
color: var(--black);
margin-left: 6px;
}
}
.chat-message-container {
@@ -413,21 +407,6 @@
margin-top: 5px;
}
.chat-message-tools {
font-size: 12px;
color: #aaa;
line-height: 1.5;
margin-top: 5px;
.chat-message-tool {
display: flex;
align-items: end;
svg {
margin-left: 5px;
margin-right: 5px;
}
}
}
.chat-message-item {
box-sizing: border-box;
max-width: 100%;
@@ -645,52 +624,4 @@
.chat-input-send {
bottom: 30px;
}
}
.shortcut-key-container {
padding: 10px;
overflow-y: auto;
display: flex;
flex-direction: column;
}
.shortcut-key-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
gap: 16px;
}
.shortcut-key-item {
display: flex;
justify-content: space-between;
align-items: center;
overflow: hidden;
padding: 10px;
background-color: var(--white);
}
.shortcut-key-title {
font-size: 14px;
color: var(--black);
}
.shortcut-key-keys {
display: flex;
gap: 8px;
}
.shortcut-key {
display: flex;
align-items: center;
justify-content: center;
border: var(--border-in-light);
border-radius: 8px;
padding: 4px;
background-color: var(--gray);
min-width: 32px;
}
.shortcut-key span {
font-size: 12px;
color: var(--black);
}

View File

@@ -28,7 +28,6 @@ import DeleteIcon from "../icons/clear.svg";
import PinIcon from "../icons/pin.svg";
import EditIcon from "../icons/rename.svg";
import ConfirmIcon from "../icons/confirm.svg";
import CloseIcon from "../icons/close.svg";
import CancelIcon from "../icons/cancel.svg";
import ImageIcon from "../icons/image.svg";
@@ -38,11 +37,6 @@ import AutoIcon from "../icons/auto.svg";
import BottomIcon from "../icons/bottom.svg";
import StopIcon from "../icons/pause.svg";
import RobotIcon from "../icons/robot.svg";
import SizeIcon from "../icons/size.svg";
import QualityIcon from "../icons/hd.svg";
import StyleIcon from "../icons/palette.svg";
import PluginIcon from "../icons/plugin.svg";
import ShortcutkeyIcon from "../icons/shortcutkey.svg";
import {
ChatMessage,
@@ -55,7 +49,6 @@ import {
useAppConfig,
DEFAULT_TOPIC,
ModelType,
usePluginStore,
} from "../store";
import {
@@ -66,17 +59,12 @@ import {
getMessageTextContent,
getMessageImages,
isVisionModel,
isDalle3,
showPlugins,
safeLocalStorage,
compressImage,
} from "../utils";
import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
import dynamic from "next/dynamic";
import { ChatControllerPool } from "../client/controller";
import { DalleSize, DalleQuality, DalleStyle } from "../typing";
import { Prompt, usePromptStore } from "../store/prompt";
import Locale from "../locales";
@@ -99,7 +87,6 @@ import {
Path,
REQUEST_TIMEOUT_MS,
UNFINISHED_INPUT,
ServiceProvider,
} from "../constant";
import { Avatar } from "./emoji";
import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask";
@@ -111,8 +98,6 @@ import { getClientConfig } from "../config/client";
import { useAllModels } from "../utils/hooks";
import { MultimodalContent } from "../client/api";
const localStorage = safeLocalStorage();
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
});
@@ -192,7 +177,7 @@ function PromptToast(props: {
return (
<div className={styles["prompt-toast"]} key="prompt-toast">
{props.showToast && context.length > 0 && (
{props.showToast && (
<div
className={styles["prompt-toast-inner"] + " clickable"}
role="button"
@@ -258,11 +243,11 @@ function useSubmitHandler() {
};
}
export type RenderPrompt = Pick<Prompt, "title" | "content">;
export type RenderPompt = Pick<Prompt, "title" | "content">;
export function PromptHints(props: {
prompts: RenderPrompt[];
onPromptSelect: (prompt: RenderPrompt) => void;
prompts: RenderPompt[];
onPromptSelect: (prompt: RenderPompt) => void;
}) {
const noPrompts = props.prompts.length === 0;
const [selectIndex, setSelectIndex] = useState(0);
@@ -351,7 +336,7 @@ function ClearContextDivider() {
);
}
export function ChatAction(props: {
function ChatAction(props: {
text: string;
icon: JSX.Element;
onClick: () => void;
@@ -441,12 +426,10 @@ export function ChatActions(props: {
showPromptHints: () => void;
hitBottom: boolean;
uploading: boolean;
setShowShortcutKeyModal: React.Dispatch<React.SetStateAction<boolean>>;
}) {
const config = useAppConfig();
const navigate = useNavigate();
const chatStore = useChatStore();
const pluginStore = usePluginStore();
// switch themes
const theme = config.theme;
@@ -464,9 +447,6 @@ export function ChatActions(props: {
// switch model
const currentModel = chatStore.currentSession().mask.modelConfig.model;
const currentProviderName =
chatStore.currentSession().mask.modelConfig?.providerName ||
ServiceProvider.OpenAI;
const allModels = useAllModels();
const models = useMemo(() => {
const filteredModels = allModels.filter((m) => m.available);
@@ -482,33 +462,9 @@ export function ChatActions(props: {
return filteredModels;
}
}, [allModels]);
const currentModelName = useMemo(() => {
const model = models.find(
(m) =>
m.name == currentModel &&
m?.provider?.providerName == currentProviderName,
);
return model?.displayName ?? "";
}, [models, currentModel, currentProviderName]);
const [showModelSelector, setShowModelSelector] = useState(false);
const [showPluginSelector, setShowPluginSelector] = useState(false);
const [showUploadImage, setShowUploadImage] = useState(false);
const [showSizeSelector, setShowSizeSelector] = useState(false);
const [showQualitySelector, setShowQualitySelector] = useState(false);
const [showStyleSelector, setShowStyleSelector] = useState(false);
const dalle3Sizes: DalleSize[] = ["1024x1024", "1792x1024", "1024x1792"];
const dalle3Qualitys: DalleQuality[] = ["standard", "hd"];
const dalle3Styles: DalleStyle[] = ["vivid", "natural"];
const currentSize =
chatStore.currentSession().mask.modelConfig?.size ?? "1024x1024";
const currentQuality =
chatStore.currentSession().mask.modelConfig?.quality ?? "standard";
const currentStyle =
chatStore.currentSession().mask.modelConfig?.style ?? "vivid";
const isMobileScreen = useMobileScreen();
useEffect(() => {
const show = isVisionModel(currentModel);
setShowUploadImage(show);
@@ -522,17 +478,13 @@ export function ChatActions(props: {
const isUnavaliableModel = !models.some((m) => m.name === currentModel);
if (isUnavaliableModel && models.length > 0) {
// show next model to default model if exist
let nextModel = models.find((model) => model.isDefault) || models[0];
chatStore.updateCurrentSession((session) => {
session.mask.modelConfig.model = nextModel.name;
session.mask.modelConfig.providerName = nextModel?.provider
?.providerName as ServiceProvider;
});
showToast(
nextModel?.provider?.providerName == "ByteDance"
? nextModel.displayName
: nextModel.name,
let nextModel: ModelType = (
models.find((model) => model.isDefault) || models[0]
).name;
chatStore.updateCurrentSession(
(session) => (session.mask.modelConfig.model = nextModel),
);
showToast(nextModel);
}
}, [chatStore, currentModel, models]);
@@ -614,162 +566,28 @@ export function ChatActions(props: {
<ChatAction
onClick={() => setShowModelSelector(true)}
text={currentModelName}
text={currentModel}
icon={<RobotIcon />}
/>
{showModelSelector && (
<Selector
defaultSelectedValue={`${currentModel}@${currentProviderName}`}
defaultSelectedValue={currentModel}
items={models.map((m) => ({
title: `${m.displayName}${
m?.provider?.providerName
? "(" + m?.provider?.providerName + ")"
: ""
}`,
value: `${m.name}@${m?.provider?.providerName}`,
title: m.displayName,
value: m.name,
}))}
onClose={() => setShowModelSelector(false)}
onSelection={(s) => {
if (s.length === 0) return;
const [model, providerName] = s[0].split("@");
chatStore.updateCurrentSession((session) => {
session.mask.modelConfig.model = model as ModelType;
session.mask.modelConfig.providerName =
providerName as ServiceProvider;
session.mask.modelConfig.model = s[0] as ModelType;
session.mask.syncGlobalConfig = false;
});
if (providerName == "ByteDance") {
const selectedModel = models.find(
(m) =>
m.name == model && m?.provider?.providerName == providerName,
);
showToast(selectedModel?.displayName ?? "");
} else {
showToast(model);
}
showToast(s[0]);
}}
/>
)}
{isDalle3(currentModel) && (
<ChatAction
onClick={() => setShowSizeSelector(true)}
text={currentSize}
icon={<SizeIcon />}
/>
)}
{showSizeSelector && (
<Selector
defaultSelectedValue={currentSize}
items={dalle3Sizes.map((m) => ({
title: m,
value: m,
}))}
onClose={() => setShowSizeSelector(false)}
onSelection={(s) => {
if (s.length === 0) return;
const size = s[0];
chatStore.updateCurrentSession((session) => {
session.mask.modelConfig.size = size;
});
showToast(size);
}}
/>
)}
{isDalle3(currentModel) && (
<ChatAction
onClick={() => setShowQualitySelector(true)}
text={currentQuality}
icon={<QualityIcon />}
/>
)}
{showQualitySelector && (
<Selector
defaultSelectedValue={currentQuality}
items={dalle3Qualitys.map((m) => ({
title: m,
value: m,
}))}
onClose={() => setShowQualitySelector(false)}
onSelection={(q) => {
if (q.length === 0) return;
const quality = q[0];
chatStore.updateCurrentSession((session) => {
session.mask.modelConfig.quality = quality;
});
showToast(quality);
}}
/>
)}
{isDalle3(currentModel) && (
<ChatAction
onClick={() => setShowStyleSelector(true)}
text={currentStyle}
icon={<StyleIcon />}
/>
)}
{showStyleSelector && (
<Selector
defaultSelectedValue={currentStyle}
items={dalle3Styles.map((m) => ({
title: m,
value: m,
}))}
onClose={() => setShowStyleSelector(false)}
onSelection={(s) => {
if (s.length === 0) return;
const style = s[0];
chatStore.updateCurrentSession((session) => {
session.mask.modelConfig.style = style;
});
showToast(style);
}}
/>
)}
{showPlugins(currentProviderName, currentModel) && (
<ChatAction
onClick={() => {
if (pluginStore.getAll().length == 0) {
navigate(Path.Plugins);
} else {
setShowPluginSelector(true);
}
}}
text={Locale.Plugin.Name}
icon={<PluginIcon />}
/>
)}
{showPluginSelector && (
<Selector
multiple
defaultSelectedValue={chatStore.currentSession().mask?.plugin}
items={pluginStore.getAll().map((item) => ({
title: `${item?.title}@${item?.version}`,
value: item?.id,
}))}
onClose={() => setShowPluginSelector(false)}
onSelection={(s) => {
chatStore.updateCurrentSession((session) => {
session.mask.plugin = s as string[];
});
}}
/>
)}
{!isMobileScreen && (
<ChatAction
onClick={() => props.setShowShortcutKeyModal(true)}
text={Locale.Chat.ShortcutKey.Title}
icon={<ShortcutkeyIcon />}
/>
)}
</div>
);
}
@@ -844,67 +662,6 @@ export function DeleteImageButton(props: { deleteImage: () => void }) {
);
}
export function ShortcutKeyModal(props: { onClose: () => void }) {
const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;
const shortcuts = [
{
title: Locale.Chat.ShortcutKey.newChat,
keys: isMac ? ["⌘", "Shift", "O"] : ["Ctrl", "Shift", "O"],
},
{ title: Locale.Chat.ShortcutKey.focusInput, keys: ["Shift", "Esc"] },
{
title: Locale.Chat.ShortcutKey.copyLastCode,
keys: isMac ? ["⌘", "Shift", ";"] : ["Ctrl", "Shift", ";"],
},
{
title: Locale.Chat.ShortcutKey.copyLastMessage,
keys: isMac ? ["⌘", "Shift", "C"] : ["Ctrl", "Shift", "C"],
},
{
title: Locale.Chat.ShortcutKey.showShortcutKey,
keys: isMac ? ["⌘", "/"] : ["Ctrl", "/"],
},
];
return (
<div className="modal-mask">
<Modal
title={Locale.Chat.ShortcutKey.Title}
onClose={props.onClose}
actions={[
<IconButton
type="primary"
text={Locale.UI.Confirm}
icon={<ConfirmIcon />}
key="ok"
onClick={() => {
props.onClose();
}}
/>,
]}
>
<div className={styles["shortcut-key-container"]}>
<div className={styles["shortcut-key-grid"]}>
{shortcuts.map((shortcut, index) => (
<div key={index} className={styles["shortcut-key-item"]}>
<div className={styles["shortcut-key-title"]}>
{shortcut.title}
</div>
<div className={styles["shortcut-key-keys"]}>
{shortcut.keys.map((key, i) => (
<div key={i} className={styles["shortcut-key"]}>
<span>{key}</span>
</div>
))}
</div>
</div>
))}
</div>
</div>
</Modal>
</div>
);
}
function _Chat() {
type RenderMessage = ChatMessage & { preview?: boolean };
@@ -912,7 +669,6 @@ function _Chat() {
const session = chatStore.currentSession();
const config = useAppConfig();
const fontSize = config.fontSize;
const fontFamily = config.fontFamily;
const [showExport, setShowExport] = useState(false);
@@ -939,7 +695,7 @@ function _Chat() {
// prompt hints
const promptStore = usePromptStore();
const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
const [promptHints, setPromptHints] = useState<RenderPompt[]>([]);
const onSearch = useDebouncedCallback(
(text: string) => {
const matchedPrompts = promptStore.search(text);
@@ -992,7 +748,7 @@ function _Chat() {
// clear search results
if (n === 0) {
setPromptHints([]);
} else if (text.match(ChatCommandPrefix)) {
} else if (text.startsWith(ChatCommandPrefix)) {
setPromptHints(chatCommands.search(text));
} else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
// check if need to trigger auto completion
@@ -1017,14 +773,14 @@ function _Chat() {
.onUserInput(userInput, attachImages)
.then(() => setIsLoading(false));
setAttachImages([]);
chatStore.setLastInput(userInput);
localStorage.setItem(LAST_INPUT_KEY, userInput);
setUserInput("");
setPromptHints([]);
if (!isMobileScreen) inputRef.current?.focus();
setAutoScroll(true);
};
const onPromptSelect = (prompt: RenderPrompt) => {
const onPromptSelect = (prompt: RenderPompt) => {
setTimeout(() => {
setPromptHints([]);
@@ -1083,7 +839,7 @@ function _Chat() {
userInput.length <= 0 &&
!(e.metaKey || e.altKey || e.ctrlKey)
) {
setUserInput(chatStore.lastInput ?? "");
setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
e.preventDefault();
return;
}
@@ -1379,7 +1135,7 @@ function _Chat() {
...(await new Promise<string[]>((res, rej) => {
setUploading(true);
const imagesData: string[] = [];
uploadImageRemote(file)
compressImage(file, 256 * 1024)
.then((dataUrl) => {
imagesData.push(dataUrl);
setUploading(false);
@@ -1421,7 +1177,7 @@ function _Chat() {
const imagesData: string[] = [];
for (let i = 0; i < files.length; i++) {
const file = event.target.files[i];
uploadImageRemote(file)
compressImage(file, 256 * 1024)
.then((dataUrl) => {
imagesData.push(dataUrl);
if (
@@ -1449,70 +1205,6 @@ function _Chat() {
setAttachImages(images);
}
// 快捷键 shortcut keys
const [showShortcutKeyModal, setShowShortcutKeyModal] = useState(false);
useEffect(() => {
const handleKeyDown = (event: any) => {
// 打开新聊天 command + shift + o
if (
(event.metaKey || event.ctrlKey) &&
event.shiftKey &&
event.key.toLowerCase() === "o"
) {
event.preventDefault();
setTimeout(() => {
chatStore.newSession();
navigate(Path.Chat);
}, 10);
}
// 聚焦聊天输入 shift + esc
else if (event.shiftKey && event.key.toLowerCase() === "escape") {
event.preventDefault();
inputRef.current?.focus();
}
// 复制最后一个代码块 command + shift + ;
else if (
(event.metaKey || event.ctrlKey) &&
event.shiftKey &&
event.code === "Semicolon"
) {
event.preventDefault();
const copyCodeButton =
document.querySelectorAll<HTMLElement>(".copy-code-button");
if (copyCodeButton.length > 0) {
copyCodeButton[copyCodeButton.length - 1].click();
}
}
// 复制最后一个回复 command + shift + c
else if (
(event.metaKey || event.ctrlKey) &&
event.shiftKey &&
event.key.toLowerCase() === "c"
) {
event.preventDefault();
const lastNonUserMessage = messages
.filter((message) => message.role !== "user")
.pop();
if (lastNonUserMessage) {
const lastMessageContent = getMessageTextContent(lastNonUserMessage);
copyToClipboard(lastMessageContent);
}
}
// 展示快捷键 command + /
else if ((event.metaKey || event.ctrlKey) && event.key === "/") {
event.preventDefault();
setShowShortcutKeyModal(true);
}
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [messages, chatStore, navigate]);
return (
<div className={styles.chat} key={session.id}>
<div className="window-header" data-tauri-drag-region>
@@ -1546,8 +1238,6 @@ function _Chat() {
<IconButton
icon={<RenameIcon />}
bordered
title={Locale.Chat.EditMessage.Title}
aria={Locale.Chat.EditMessage.Title}
onClick={() => setIsEditingMessage(true)}
/>
</div>
@@ -1567,8 +1257,6 @@ function _Chat() {
<IconButton
icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
bordered
title={Locale.Chat.Actions.FullScreen}
aria={Locale.Chat.Actions.FullScreen}
onClick={() => {
config.update(
(config) => (config.tightBorder = !config.tightBorder),
@@ -1620,7 +1308,6 @@ function _Chat() {
<div className={styles["chat-message-edit"]}>
<IconButton
icon={<EditIcon />}
aria={Locale.Chat.Actions.Edit}
onClick={async () => {
const newMessage = await showPrompt(
Locale.Chat.Actions.Edit,
@@ -1669,11 +1356,6 @@ function _Chat() {
</>
)}
</div>
{!isUser && (
<div className={styles["chat-model-name"]}>
{message.model}
</div>
)}
{showActions && (
<div className={styles["chat-message-actions"]}>
@@ -1718,47 +1400,25 @@ function _Chat() {
</div>
)}
</div>
{message?.tools?.length == 0 && showTyping && (
{showTyping && (
<div className={styles["chat-message-status"]}>
{Locale.Chat.Typing}
</div>
)}
{/*@ts-ignore*/}
{message?.tools?.length > 0 && (
<div className={styles["chat-message-tools"]}>
{message?.tools?.map((tool) => (
<div
key={tool.id}
className={styles["chat-message-tool"]}
>
{tool.isError === false ? (
<ConfirmIcon />
) : tool.isError === true ? (
<CloseIcon />
) : (
<LoadingButtonIcon />
)}
<span>{tool?.function?.name}</span>
</div>
))}
</div>
)}
<div className={styles["chat-message-item"]}>
<Markdown
key={message.streaming ? "loading" : "done"}
content={getMessageTextContent(message)}
loading={
(message.preview || message.streaming) &&
message.content.length === 0 &&
!isUser
}
// onContextMenu={(e) => onRightClick(e, message)} // hard to use
onContextMenu={(e) => onRightClick(e, message)}
onDoubleClickCapture={() => {
if (!isMobileScreen) return;
setUserInput(getMessageTextContent(message));
}}
fontSize={fontSize}
fontFamily={fontFamily}
parentRef={scrollRef}
defaultShow={i >= messages.length - 6}
/>
@@ -1829,7 +1489,6 @@ function _Chat() {
setUserInput("/");
onSearch("");
}}
setShowShortcutKeyModal={setShowShortcutKeyModal}
/>
<label
className={`${styles["chat-input-panel-inner"]} ${
@@ -1854,7 +1513,6 @@ function _Chat() {
autoFocus={autoFocus}
style={{
fontSize: config.fontSize,
fontFamily: config.fontFamily,
}}
/>
{attachImages.length != 0 && (
@@ -1901,10 +1559,6 @@ function _Chat() {
}}
/>
)}
{showShortcutKeyModal && (
<ShortcutKeyModal onClose={() => setShowShortcutKeyModal(false)} />
)}
</div>
);
}

View File

@@ -36,8 +36,7 @@ export function Avatar(props: { model?: ModelType; avatar?: string }) {
if (props.model) {
return (
<div className="no-dark">
{props.model?.startsWith("gpt-4") ||
props.model?.startsWith("chatgpt-4o") ? (
{props.model?.startsWith("gpt-4") ? (
<BlackBotIcon className="user-avatar" />
) : (
<BotIcon className="user-avatar" />

View File

@@ -1,5 +1,3 @@
"use client";
import React from "react";
import { IconButton } from "./button";
import GithubIcon from "../icons/github.svg";
@@ -8,7 +6,6 @@ import { ISSUE_URL } from "../constant";
import Locale from "../locales";
import { showConfirm } from "./ui-lib";
import { useSyncStore } from "../store/sync";
import { useChatStore } from "../store/chat";
interface IErrorBoundaryState {
hasError: boolean;
@@ -31,7 +28,8 @@ export class ErrorBoundary extends React.Component<any, IErrorBoundaryState> {
try {
useSyncStore.getState().export();
} finally {
useChatStore.getState().clearAllData();
localStorage.clear();
location.reload();
}
}

View File

@@ -36,10 +36,11 @@ import { toBlob, toPng } from "html-to-image";
import { DEFAULT_MASK_AVATAR } from "../store/mask";
import { prettyObject } from "../utils/format";
import { EXPORT_MESSAGE_CLASS_NAME } from "../constant";
import { EXPORT_MESSAGE_CLASS_NAME, ModelProvider } from "../constant";
import { getClientConfig } from "../config/client";
import { type ClientApi, getClientApi } from "../client/api";
import { ClientApi } from "../client/api";
import { getMessageTextContent } from "../utils";
import { identifyDefaultClaudeModel } from "../utils/checkers";
const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
loading: () => <LoadingIcon />,
@@ -312,7 +313,14 @@ export function PreviewActions(props: {
const onRenderMsgs = (msgs: ChatMessage[]) => {
setShouldExport(false);
const api: ClientApi = getClientApi(config.modelConfig.providerName);
var api: ClientApi;
if (config.modelConfig.model.startsWith("gemini")) {
api = new ClientApi(ModelProvider.GeminiPro);
} else if (identifyDefaultClaudeModel(config.modelConfig.model)) {
api = new ClientApi(ModelProvider.Claude);
} else {
api = new ClientApi(ModelProvider.GPT);
}
api
.share(msgs)
@@ -541,7 +549,7 @@ export function ImagePreviewer(props: {
<div>
<div className={styles["main-title"]}>NextChat</div>
<div className={styles["sub-title"]}>
github.com/ChatGPTNextWeb/ChatGPT-Next-Web
github.com/Yidadaa/ChatGPT-Next-Web
</div>
<div className={styles["icons"]}>
<ExportAvatar avatar={config.avatar} />
@@ -583,7 +591,6 @@ export function ImagePreviewer(props: {
<Markdown
content={getMessageTextContent(m)}
fontSize={config.fontSize}
fontFamily={config.fontFamily}
defaultShow
/>
{getMessageImages(m).length == 1 && (

View File

@@ -137,18 +137,12 @@
position: relative;
padding-top: 20px;
padding-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.sidebar-logo {
display: inline-flex;
}
.sidebar-title-container {
display: inline-flex;
flex-direction: column;
position: absolute;
right: 0;
bottom: 18px;
}
.sidebar-title {

View File

@@ -12,7 +12,7 @@ import LoadingIcon from "../icons/three-dots.svg";
import { getCSSVar, useMobileScreen } from "../utils";
import dynamic from "next/dynamic";
import { Path, SlotID } from "../constant";
import { ModelProvider, Path, SlotID } from "../constant";
import { ErrorBoundary } from "./error";
import { getISOLang, getLang } from "../locales";
@@ -27,8 +27,9 @@ import { SideBar } from "./sidebar";
import { useAppConfig } from "../store/config";
import { AuthPage } from "./auth";
import { getClientConfig } from "../config/client";
import { type ClientApi, getClientApi } from "../client/api";
import { ClientApi } from "../client/api";
import { useAccessStore } from "../store";
import { identifyDefaultClaudeModel } from "../utils/checkers";
export function Loading(props: { noLogo?: boolean }) {
return (
@@ -39,10 +40,6 @@ export function Loading(props: { noLogo?: boolean }) {
);
}
const Artifacts = dynamic(async () => (await import("./artifacts")).Artifacts, {
loading: () => <Loading noLogo />,
});
const Settings = dynamic(async () => (await import("./settings")).Settings, {
loading: () => <Loading noLogo />,
});
@@ -59,21 +56,6 @@ const MaskPage = dynamic(async () => (await import("./mask")).MaskPage, {
loading: () => <Loading noLogo />,
});
const PluginPage = dynamic(async () => (await import("./plugin")).PluginPage, {
loading: () => <Loading noLogo />,
});
const SearchChat = dynamic(
async () => (await import("./search-chat")).SearchChatPage,
{
loading: () => <Loading noLogo />,
},
);
const Sd = dynamic(async () => (await import("./sd")).Sd, {
loading: () => <Loading noLogo />,
});
export function useSwitchTheme() {
const config = useAppConfig();
@@ -141,23 +123,11 @@ const loadAsyncGoogleFont = () => {
document.head.appendChild(linkEl);
};
export function WindowContent(props: { children: React.ReactNode }) {
return (
<div className={styles["window-content"]} id={SlotID.AppBody}>
{props?.children}
</div>
);
}
function Screen() {
const config = useAppConfig();
const location = useLocation();
const isArtifact = location.pathname.includes(Path.Artifacts);
const isHome = location.pathname === Path.Home;
const isAuth = location.pathname === Path.Auth;
const isSd = location.pathname === Path.Sd;
const isSdNew = location.pathname === Path.SdNew;
const isMobileScreen = useMobileScreen();
const shouldTightBorder =
getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen);
@@ -166,42 +136,34 @@ function Screen() {
loadAsyncGoogleFont();
}, []);
if (isArtifact) {
return (
<Routes>
<Route path="/artifacts/:id" element={<Artifacts />} />
</Routes>
);
}
const renderContent = () => {
if (isAuth) return <AuthPage />;
if (isSd) return <Sd />;
if (isSdNew) return <Sd />;
return (
<>
<SideBar className={isHome ? styles["sidebar-show"] : ""} />
<WindowContent>
<Routes>
<Route path={Path.Home} element={<Chat />} />
<Route path={Path.NewChat} element={<NewChat />} />
<Route path={Path.Masks} element={<MaskPage />} />
<Route path={Path.Plugins} element={<PluginPage />} />
<Route path={Path.SearchChat} element={<SearchChat />} />
<Route path={Path.Chat} element={<Chat />} />
<Route path={Path.Settings} element={<Settings />} />
</Routes>
</WindowContent>
</>
);
};
return (
<div
className={`${styles.container} ${
shouldTightBorder ? styles["tight-container"] : styles.container
} ${getLang() === "ar" ? styles["rtl-screen"] : ""}`}
className={
styles.container +
` ${shouldTightBorder ? styles["tight-container"] : styles.container} ${
getLang() === "ar" ? styles["rtl-screen"] : ""
}`
}
>
{renderContent()}
{isAuth ? (
<>
<AuthPage />
</>
) : (
<>
<SideBar className={isHome ? styles["sidebar-show"] : ""} />
<div className={styles["window-content"]} id={SlotID.AppBody}>
<Routes>
<Route path={Path.Home} element={<Chat />} />
<Route path={Path.NewChat} element={<NewChat />} />
<Route path={Path.Masks} element={<MaskPage />} />
<Route path={Path.Chat} element={<Chat />} />
<Route path={Path.Settings} element={<Settings />} />
</Routes>
</div>
</>
)}
</div>
);
}
@@ -209,8 +171,14 @@ function Screen() {
export function useLoadData() {
const config = useAppConfig();
const api: ClientApi = getClientApi(config.modelConfig.providerName);
var api: ClientApi;
if (config.modelConfig.model.startsWith("gemini")) {
api = new ClientApi(ModelProvider.GeminiPro);
} else if (identifyDefaultClaudeModel(config.modelConfig.model)) {
api = new ClientApi(ModelProvider.Claude);
} else {
api = new ClientApi(ModelProvider.GPT);
}
useEffect(() => {
(async () => {
const models = await api.llm.models();

View File

@@ -9,7 +9,6 @@ interface InputRangeProps {
min: string;
max: string;
step: string;
aria: string;
}
export function InputRange({
@@ -20,13 +19,11 @@ export function InputRange({
min,
max,
step,
aria,
}: InputRangeProps) {
return (
<div className={styles["input-range"] + ` ${className ?? ""}`}>
{title || value}
<input
aria-label={aria}
type="range"
title={title}
value={value}

View File

@@ -6,21 +6,13 @@ import RehypeKatex from "rehype-katex";
import RemarkGfm from "remark-gfm";
import RehypeHighlight from "rehype-highlight";
import { useRef, useState, RefObject, useEffect, useMemo } from "react";
import { copyToClipboard, useWindowSize } from "../utils";
import { copyToClipboard } from "../utils";
import mermaid from "mermaid";
import Locale from "../locales";
import LoadingIcon from "../icons/three-dots.svg";
import ReloadButtonIcon from "../icons/reload.svg";
import React from "react";
import { useDebouncedCallback } from "use-debounce";
import { showImageModal, FullScreen } from "./ui-lib";
import {
ArtifactsShareButton,
HTMLPreview,
HTMLPreviewHander,
} from "./artifacts";
import { useChatStore } from "../store";
import { IconButton } from "./button";
import { showImageModal } from "./ui-lib";
export function Mermaid(props: { code: string }) {
const ref = useRef<HTMLDivElement>(null);
@@ -70,59 +62,27 @@ export function Mermaid(props: { code: string }) {
export function PreCode(props: { children: any }) {
const ref = useRef<HTMLPreElement>(null);
const previewRef = useRef<HTMLPreviewHander>(null);
const refText = ref.current?.innerText;
const [mermaidCode, setMermaidCode] = useState("");
const [htmlCode, setHtmlCode] = useState("");
const { height } = useWindowSize();
const chatStore = useChatStore();
const session = chatStore.currentSession();
const renderArtifacts = useDebouncedCallback(() => {
const renderMermaid = useDebouncedCallback(() => {
if (!ref.current) return;
const mermaidDom = ref.current.querySelector("code.language-mermaid");
if (mermaidDom) {
setMermaidCode((mermaidDom as HTMLElement).innerText);
}
const htmlDom = ref.current.querySelector("code.language-html");
const refText = ref.current.querySelector("code")?.innerText;
if (htmlDom) {
setHtmlCode((htmlDom as HTMLElement).innerText);
} else if (refText?.startsWith("<!DOCTYPE")) {
setHtmlCode(refText);
}
}, 600);
const enableArtifacts = session.mask?.enableArtifacts !== false;
//Wrap the paragraph for plain-text
useEffect(() => {
if (ref.current) {
const codeElements = ref.current.querySelectorAll(
"code",
) as NodeListOf<HTMLElement>;
const wrapLanguages = [
"",
"md",
"markdown",
"text",
"txt",
"plaintext",
"tex",
"latex",
];
codeElements.forEach((codeElement) => {
let languageClass = codeElement.className.match(/language-(\w+)/);
let name = languageClass ? languageClass[1] : "";
if (wrapLanguages.includes(name)) {
codeElement.style.whiteSpace = "pre-wrap";
}
});
setTimeout(renderArtifacts, 1);
}
}, []);
setTimeout(renderMermaid, 1);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [refText]);
return (
<>
{mermaidCode.length > 0 && (
<Mermaid code={mermaidCode} key={mermaidCode} />
)}
<pre ref={ref}>
<span
className="copy-code-button"
@@ -135,69 +95,6 @@ export function PreCode(props: { children: any }) {
></span>
{props.children}
</pre>
{mermaidCode.length > 0 && (
<Mermaid code={mermaidCode} key={mermaidCode} />
)}
{htmlCode.length > 0 && enableArtifacts && (
<FullScreen className="no-dark html" right={70}>
<ArtifactsShareButton
style={{ position: "absolute", right: 20, top: 10 }}
getCode={() => htmlCode}
/>
<IconButton
style={{ position: "absolute", right: 120, top: 10 }}
bordered
icon={<ReloadButtonIcon />}
shadow
onClick={() => previewRef.current?.reload()}
/>
<HTMLPreview
ref={previewRef}
code={htmlCode}
autoHeight={!document.fullscreenElement}
height={!document.fullscreenElement ? 600 : height}
/>
</FullScreen>
)}
</>
);
}
function CustomCode(props: { children: any; className?: string }) {
const ref = useRef<HTMLPreElement>(null);
const [collapsed, setCollapsed] = useState(true);
const [showToggle, setShowToggle] = useState(false);
useEffect(() => {
if (ref.current) {
const codeHeight = ref.current.scrollHeight;
setShowToggle(codeHeight > 400);
ref.current.scrollTop = ref.current.scrollHeight;
}
}, [props.children]);
const toggleCollapsed = () => {
setCollapsed((collapsed) => !collapsed);
};
return (
<>
<code
className={props?.className}
ref={ref}
style={{
maxHeight: collapsed ? "400px" : "none",
overflowY: "hidden",
}}
>
{props.children}
</code>
{showToggle && collapsed && (
<div
className={`show-hide-button ${collapsed ? "collapsed" : "expanded"}`}
>
<button onClick={toggleCollapsed}>{Locale.NewChat.More}</button>
</div>
)}
</>
);
}
@@ -237,26 +134,9 @@ function escapeBrackets(text: string) {
);
}
function tryWrapHtmlCode(text: string) {
// try add wrap html code (fixed: html codeblock include 2 newline)
return text
.replace(
/([`]*?)(\w*?)([\n\r]*?)(<!DOCTYPE html>)/g,
(match, quoteStart, lang, newLine, doctype) => {
return !quoteStart ? "\n```html\n" + doctype : match;
},
)
.replace(
/(<\/body>)([\r\n\s]*?)(<\/html>)([\n\r]*?)([`]*?)([\n\r]*?)/g,
(match, bodyEnd, space, htmlEnd, newLine, quoteEnd) => {
return !quoteEnd ? bodyEnd + space + htmlEnd + "\n```\n" : match;
},
);
}
function _MarkDownContent(props: { content: string }) {
const escapedContent = useMemo(() => {
return tryWrapHtmlCode(escapeBrackets(escapeDollarNumber(props.content)));
return escapeBrackets(escapeDollarNumber(props.content));
}, [props.content]);
return (
@@ -274,7 +154,6 @@ function _MarkDownContent(props: { content: string }) {
]}
components={{
pre: PreCode,
code: CustomCode,
p: (pProps) => <p {...pProps} dir="auto" />,
a: (aProps) => {
const href = aProps.href || "";
@@ -296,7 +175,6 @@ export function Markdown(
content: string;
loading?: boolean;
fontSize?: number;
fontFamily?: string;
parentRef?: RefObject<HTMLDivElement>;
defaultShow?: boolean;
} & React.DOMAttributes<HTMLDivElement>,
@@ -308,7 +186,6 @@ export function Markdown(
className="markdown-body"
style={{
fontSize: `${props.fontSize ?? 14}px`,
fontFamily: props.fontFamily || "inherit",
}}
ref={mdRef}
onContextMenu={props.onContextMenu}

View File

@@ -127,8 +127,6 @@ export function MaskConfig(props: {
onClose={() => setShowPicker(false)}
>
<div
tabIndex={0}
aria-label={Locale.Mask.Config.Avatar}
onClick={() => setShowPicker(true)}
style={{ cursor: "pointer" }}
>
@@ -141,7 +139,6 @@ export function MaskConfig(props: {
</ListItem>
<ListItem title={Locale.Mask.Config.Name}>
<input
aria-label={Locale.Mask.Config.Name}
type="text"
value={props.mask.name}
onInput={(e) =>
@@ -156,7 +153,6 @@ export function MaskConfig(props: {
subTitle={Locale.Mask.Config.HideContext.SubTitle}
>
<input
aria-label={Locale.Mask.Config.HideContext.Title}
type="checkbox"
checked={props.mask.hideContext}
onChange={(e) => {
@@ -167,29 +163,12 @@ export function MaskConfig(props: {
></input>
</ListItem>
<ListItem
title={Locale.Mask.Config.Artifacts.Title}
subTitle={Locale.Mask.Config.Artifacts.SubTitle}
>
<input
aria-label={Locale.Mask.Config.Artifacts.Title}
type="checkbox"
checked={props.mask.enableArtifacts !== false}
onChange={(e) => {
props.updateMask((mask) => {
mask.enableArtifacts = e.currentTarget.checked;
});
}}
></input>
</ListItem>
{!props.shouldSyncFromGlobal ? (
<ListItem
title={Locale.Mask.Config.Share.Title}
subTitle={Locale.Mask.Config.Share.SubTitle}
>
<IconButton
aria={Locale.Mask.Config.Share.Title}
icon={<CopyIcon />}
text={Locale.Mask.Config.Share.Action}
onClick={copyMaskLink}
@@ -203,7 +182,6 @@ export function MaskConfig(props: {
subTitle={Locale.Mask.Config.Sync.SubTitle}
>
<input
aria-label={Locale.Mask.Config.Sync.Title}
type="checkbox"
checked={props.mask.syncGlobalConfig}
onChange={async (e) => {
@@ -426,7 +404,16 @@ export function MaskPage() {
const maskStore = useMaskStore();
const chatStore = useChatStore();
const filterLang = maskStore.language;
const [filterLang, setFilterLang] = useState<Lang | undefined>(
() => localStorage.getItem("Mask-language") as Lang | undefined,
);
useEffect(() => {
if (filterLang) {
localStorage.setItem("Mask-language", filterLang);
} else {
localStorage.removeItem("Mask-language");
}
}, [filterLang]);
const allMasks = maskStore
.getAll()
@@ -533,9 +520,9 @@ export function MaskPage() {
onChange={(e) => {
const value = e.currentTarget.value;
if (value === Locale.Settings.Lang.All) {
maskStore.setLanguage(undefined);
setFilterLang(undefined);
} else {
maskStore.setLanguage(value as Lang);
setFilterLang(value as Lang);
}
}}
>

View File

@@ -1,4 +1,3 @@
import { ServiceProvider } from "@/app/constant";
import { ModalConfigValidator, ModelConfig } from "../store";
import Locale from "../locales";
@@ -11,26 +10,25 @@ export function ModelConfigList(props: {
updateConfig: (updater: (config: ModelConfig) => void) => void;
}) {
const allModels = useAllModels();
const value = `${props.modelConfig.model}@${props.modelConfig?.providerName}`;
return (
<>
<ListItem title={Locale.Settings.Model}>
<Select
aria-label={Locale.Settings.Model}
value={value}
value={props.modelConfig.model}
onChange={(e) => {
const [model, providerName] = e.currentTarget.value.split("@");
props.updateConfig((config) => {
config.model = ModalConfigValidator.model(model);
config.providerName = providerName as ServiceProvider;
});
props.updateConfig(
(config) =>
(config.model = ModalConfigValidator.model(
e.currentTarget.value,
)),
);
}}
>
{allModels
.filter((v) => v.available)
.map((v, i) => (
<option value={`${v.name}@${v.provider?.providerName}`} key={i}>
<option value={v.name} key={i}>
{v.displayName}({v.provider?.providerName})
</option>
))}
@@ -41,7 +39,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.Temperature.SubTitle}
>
<InputRange
aria={Locale.Settings.Temperature.Title}
value={props.modelConfig.temperature?.toFixed(1)}
min="0"
max="1" // lets limit it to 0-1
@@ -61,7 +58,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.TopP.SubTitle}
>
<InputRange
aria={Locale.Settings.TopP.Title}
value={(props.modelConfig.top_p ?? 1).toFixed(1)}
min="0"
max="1"
@@ -81,7 +77,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.MaxTokens.SubTitle}
>
<input
aria-label={Locale.Settings.MaxTokens.Title}
type="number"
min={1024}
max={512000}
@@ -97,14 +92,13 @@ export function ModelConfigList(props: {
></input>
</ListItem>
{props.modelConfig?.providerName == ServiceProvider.Google ? null : (
{props.modelConfig.model.startsWith("gemini") ? null : (
<>
<ListItem
title={Locale.Settings.PresencePenalty.Title}
subTitle={Locale.Settings.PresencePenalty.SubTitle}
>
<InputRange
aria={Locale.Settings.PresencePenalty.Title}
value={props.modelConfig.presence_penalty?.toFixed(1)}
min="-2"
max="2"
@@ -126,7 +120,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.FrequencyPenalty.SubTitle}
>
<InputRange
aria={Locale.Settings.FrequencyPenalty.Title}
value={props.modelConfig.frequency_penalty?.toFixed(1)}
min="-2"
max="2"
@@ -148,7 +141,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.InjectSystemPrompts.SubTitle}
>
<input
aria-label={Locale.Settings.InjectSystemPrompts.Title}
type="checkbox"
checked={props.modelConfig.enableInjectSystemPrompts}
onChange={(e) =>
@@ -166,7 +158,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.InputTemplate.SubTitle}
>
<input
aria-label={Locale.Settings.InputTemplate.Title}
type="text"
value={props.modelConfig.template}
onChange={(e) =>
@@ -183,7 +174,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.HistoryCount.SubTitle}
>
<InputRange
aria={Locale.Settings.HistoryCount.Title}
title={props.modelConfig.historyMessageCount.toString()}
value={props.modelConfig.historyMessageCount}
min="0"
@@ -202,7 +192,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.CompressThreshold.SubTitle}
>
<input
aria-label={Locale.Settings.CompressThreshold.Title}
type="number"
min={500}
max={4000}
@@ -218,7 +207,6 @@ export function ModelConfigList(props: {
</ListItem>
<ListItem title={Locale.Memory.Title} subTitle={Locale.Memory.Send}>
<input
aria-label={Locale.Memory.Title}
type="checkbox"
checked={props.modelConfig.sendMemory}
onChange={(e) =>

View File

@@ -1,16 +0,0 @@
.plugin-title {
font-weight: bolder;
font-size: 16px;
margin: 10px 0;
}
.plugin-content {
font-size: 14px;
font-family: inherit;
pre code {
max-height: 240px;
overflow-y: auto;
white-space: pre-wrap;
min-width: 300px;
}
}

View File

@@ -1,393 +0,0 @@
import { useDebouncedCallback } from "use-debounce";
import OpenAPIClientAxios from "openapi-client-axios";
import yaml from "js-yaml";
import { PLUGINS_REPO_URL } from "../constant";
import { IconButton } from "./button";
import { ErrorBoundary } from "./error";
import styles from "./mask.module.scss";
import pluginStyles from "./plugin.module.scss";
import EditIcon from "../icons/edit.svg";
import AddIcon from "../icons/add.svg";
import CloseIcon from "../icons/close.svg";
import DeleteIcon from "../icons/delete.svg";
import EyeIcon from "../icons/eye.svg";
import ConfirmIcon from "../icons/confirm.svg";
import ReloadIcon from "../icons/reload.svg";
import GithubIcon from "../icons/github.svg";
import { Plugin, usePluginStore, FunctionToolService } from "../store/plugin";
import {
PasswordInput,
List,
ListItem,
Modal,
showConfirm,
showToast,
} from "./ui-lib";
import Locale from "../locales";
import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import { getClientConfig } from "../config/client";
export function PluginPage() {
const navigate = useNavigate();
const pluginStore = usePluginStore();
const allPlugins = pluginStore.getAll();
const [searchPlugins, setSearchPlugins] = useState<Plugin[]>([]);
const [searchText, setSearchText] = useState("");
const plugins = searchText.length > 0 ? searchPlugins : allPlugins;
// refactored already, now it accurate
const onSearch = (text: string) => {
setSearchText(text);
if (text.length > 0) {
const result = allPlugins.filter(
(m) => m?.title.toLowerCase().includes(text.toLowerCase()),
);
setSearchPlugins(result);
} else {
setSearchPlugins(allPlugins);
}
};
const [editingPluginId, setEditingPluginId] = useState<string | undefined>();
const editingPlugin = pluginStore.get(editingPluginId);
const editingPluginTool = FunctionToolService.get(editingPlugin?.id);
const closePluginModal = () => setEditingPluginId(undefined);
const onChangePlugin = useDebouncedCallback((editingPlugin, e) => {
const content = e.target.innerText;
try {
const api = new OpenAPIClientAxios({
definition: yaml.load(content) as any,
});
api
.init()
.then(() => {
if (content != editingPlugin.content) {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.content = content;
const tool = FunctionToolService.add(plugin, true);
plugin.title = tool.api.definition.info.title;
plugin.version = tool.api.definition.info.version;
});
}
})
.catch((e) => {
console.error(e);
showToast(Locale.Plugin.EditModal.Error);
});
} catch (e) {
console.error(e);
showToast(Locale.Plugin.EditModal.Error);
}
}, 100).bind(null, editingPlugin);
const [loadUrl, setLoadUrl] = useState<string>("");
const loadFromUrl = (loadUrl: string) =>
fetch(loadUrl)
.catch((e) => {
const p = new URL(loadUrl);
return fetch(`/api/proxy/${p.pathname}?${p.search}`, {
headers: {
"X-Base-URL": p.origin,
},
});
})
.then((res) => res.text())
.then((content) => {
try {
return JSON.stringify(JSON.parse(content), null, " ");
} catch (e) {
return content;
}
})
.then((content) => {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.content = content;
const tool = FunctionToolService.add(plugin, true);
plugin.title = tool.api.definition.info.title;
plugin.version = tool.api.definition.info.version;
});
})
.catch((e) => {
showToast(Locale.Plugin.EditModal.Error);
});
return (
<ErrorBoundary>
<div className={styles["mask-page"]}>
<div className="window-header">
<div className="window-header-title">
<div className="window-header-main-title">
{Locale.Plugin.Page.Title}
</div>
<div className="window-header-submai-title">
{Locale.Plugin.Page.SubTitle(plugins.length)}
</div>
</div>
<div className="window-actions">
<div className="window-action-button">
<a
href={PLUGINS_REPO_URL}
target="_blank"
rel="noopener noreferrer"
>
<IconButton icon={<GithubIcon />} bordered />
</a>
</div>
<div className="window-action-button">
<IconButton
icon={<CloseIcon />}
bordered
onClick={() => navigate(-1)}
/>
</div>
</div>
</div>
<div className={styles["mask-page-body"]}>
<div className={styles["mask-filter"]}>
<input
type="text"
className={styles["search-bar"]}
placeholder={Locale.Plugin.Page.Search}
autoFocus
onInput={(e) => onSearch(e.currentTarget.value)}
/>
<IconButton
className={styles["mask-create"]}
icon={<AddIcon />}
text={Locale.Plugin.Page.Create}
bordered
onClick={() => {
const createdPlugin = pluginStore.create();
setEditingPluginId(createdPlugin.id);
}}
/>
</div>
<div>
{plugins.length == 0 && (
<div
style={{
display: "flex",
margin: "60px auto",
alignItems: "center",
justifyContent: "center",
}}
>
{Locale.Plugin.Page.Find}
<a
href={PLUGINS_REPO_URL}
target="_blank"
rel="noopener noreferrer"
style={{ marginLeft: 16 }}
>
<IconButton icon={<GithubIcon />} bordered />
</a>
</div>
)}
{plugins.map((m) => (
<div className={styles["mask-item"]} key={m.id}>
<div className={styles["mask-header"]}>
<div className={styles["mask-icon"]}></div>
<div className={styles["mask-title"]}>
<div className={styles["mask-name"]}>
{m.title}@<small>{m.version}</small>
</div>
<div className={styles["mask-info"] + " one-line"}>
{Locale.Plugin.Item.Info(
FunctionToolService.add(m).length,
)}
</div>
</div>
</div>
<div className={styles["mask-actions"]}>
{m.builtin ? (
<IconButton
icon={<EyeIcon />}
text={Locale.Plugin.Item.View}
onClick={() => setEditingPluginId(m.id)}
/>
) : (
<IconButton
icon={<EditIcon />}
text={Locale.Plugin.Item.Edit}
onClick={() => setEditingPluginId(m.id)}
/>
)}
{!m.builtin && (
<IconButton
icon={<DeleteIcon />}
text={Locale.Plugin.Item.Delete}
onClick={async () => {
if (
await showConfirm(Locale.Plugin.Item.DeleteConfirm)
) {
pluginStore.delete(m.id);
}
}}
/>
)}
</div>
</div>
))}
</div>
</div>
</div>
{editingPlugin && (
<div className="modal-mask">
<Modal
title={Locale.Plugin.EditModal.Title(editingPlugin?.builtin)}
onClose={closePluginModal}
actions={[
<IconButton
icon={<ConfirmIcon />}
text={Locale.UI.Confirm}
key="export"
bordered
onClick={() => setEditingPluginId("")}
/>,
]}
>
<List>
<ListItem title={Locale.Plugin.EditModal.Auth}>
<select
value={editingPlugin?.authType}
onChange={(e) => {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.authType = e.target.value;
});
}}
>
<option value="">{Locale.Plugin.Auth.None}</option>
<option value="bearer">{Locale.Plugin.Auth.Bearer}</option>
<option value="basic">{Locale.Plugin.Auth.Basic}</option>
<option value="custom">{Locale.Plugin.Auth.Custom}</option>
</select>
</ListItem>
{["bearer", "basic", "custom"].includes(
editingPlugin.authType as string,
) && (
<ListItem title={Locale.Plugin.Auth.Location}>
<select
value={editingPlugin?.authLocation}
onChange={(e) => {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.authLocation = e.target.value;
});
}}
>
<option value="header">
{Locale.Plugin.Auth.LocationHeader}
</option>
<option value="query">
{Locale.Plugin.Auth.LocationQuery}
</option>
<option value="body">
{Locale.Plugin.Auth.LocationBody}
</option>
</select>
</ListItem>
)}
{editingPlugin.authType == "custom" && (
<ListItem title={Locale.Plugin.Auth.CustomHeader}>
<input
type="text"
value={editingPlugin?.authHeader}
onChange={(e) => {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.authHeader = e.target.value;
});
}}
></input>
</ListItem>
)}
{["bearer", "basic", "custom"].includes(
editingPlugin.authType as string,
) && (
<ListItem title={Locale.Plugin.Auth.Token}>
<PasswordInput
type="text"
value={editingPlugin?.authToken}
onChange={(e) => {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.authToken = e.currentTarget.value;
});
}}
></PasswordInput>
</ListItem>
)}
{!getClientConfig()?.isApp && (
<ListItem
title={Locale.Plugin.Auth.Proxy}
subTitle={Locale.Plugin.Auth.ProxyDescription}
>
<input
type="checkbox"
checked={editingPlugin?.usingProxy}
style={{ minWidth: 16 }}
onChange={(e) => {
pluginStore.updatePlugin(editingPlugin.id, (plugin) => {
plugin.usingProxy = e.currentTarget.checked;
});
}}
></input>
</ListItem>
)}
</List>
<List>
<ListItem title={Locale.Plugin.EditModal.Content}>
<div style={{ display: "flex", justifyContent: "flex-end" }}>
<input
type="text"
style={{ minWidth: 200, marginRight: 20 }}
onInput={(e) => setLoadUrl(e.currentTarget.value)}
></input>
<IconButton
icon={<ReloadIcon />}
text={Locale.Plugin.EditModal.Load}
bordered
onClick={() => loadFromUrl(loadUrl)}
/>
</div>
</ListItem>
<ListItem
subTitle={
<div
className={`markdown-body ${pluginStyles["plugin-content"]}`}
dir="auto"
>
<pre>
<code
contentEditable={true}
dangerouslySetInnerHTML={{
__html: editingPlugin.content,
}}
onBlur={onChangePlugin}
></code>
</pre>
</div>
}
></ListItem>
{editingPluginTool?.tools.map((tool, index) => (
<ListItem
key={index}
title={tool?.function?.name}
subTitle={tool?.function?.description}
/>
))}
</List>
</Modal>
</div>
)}
</ErrorBoundary>
);
}

View File

@@ -1,2 +0,0 @@
export * from "./sd";
export * from "./sd-panel";

View File

@@ -1,45 +0,0 @@
.ctrl-param-item {
display: flex;
justify-content: space-between;
min-height: 40px;
padding: 10px 0;
animation: slide-in ease 0.6s;
flex-direction: column;
.ctrl-param-item-header {
display: flex;
align-items: center;
.ctrl-param-item-title {
font-size: 14px;
font-weight: bolder;
margin-bottom: 5px;
}
}
.ctrl-param-item-sub-title {
font-size: 12px;
font-weight: normal;
margin-top: 3px;
}
textarea {
appearance: none;
border-radius: 10px;
border: var(--border-in-light);
min-height: 36px;
box-sizing: border-box;
background: var(--white);
color: var(--black);
padding: 0 10px;
max-width: 50%;
font-family: inherit;
}
}
.ai-models {
button {
margin-bottom: 10px;
padding: 10px;
width: 100%;
}
}

View File

@@ -1,320 +0,0 @@
import styles from "./sd-panel.module.scss";
import React from "react";
import { Select } from "@/app/components/ui-lib";
import { IconButton } from "@/app/components/button";
import Locale from "@/app/locales";
import { useSdStore } from "@/app/store/sd";
export const params = [
{
name: Locale.SdPanel.Prompt,
value: "prompt",
type: "textarea",
placeholder: Locale.SdPanel.PleaseInput(Locale.SdPanel.Prompt),
required: true,
},
{
name: Locale.SdPanel.ModelVersion,
value: "model",
type: "select",
default: "sd3-medium",
support: ["sd3"],
options: [
{ name: "SD3 Medium", value: "sd3-medium" },
{ name: "SD3 Large", value: "sd3-large" },
{ name: "SD3 Large Turbo", value: "sd3-large-turbo" },
],
},
{
name: Locale.SdPanel.NegativePrompt,
value: "negative_prompt",
type: "textarea",
placeholder: Locale.SdPanel.PleaseInput(Locale.SdPanel.NegativePrompt),
},
{
name: Locale.SdPanel.AspectRatio,
value: "aspect_ratio",
type: "select",
default: "1:1",
options: [
{ name: "1:1", value: "1:1" },
{ name: "16:9", value: "16:9" },
{ name: "21:9", value: "21:9" },
{ name: "2:3", value: "2:3" },
{ name: "3:2", value: "3:2" },
{ name: "4:5", value: "4:5" },
{ name: "5:4", value: "5:4" },
{ name: "9:16", value: "9:16" },
{ name: "9:21", value: "9:21" },
],
},
{
name: Locale.SdPanel.ImageStyle,
value: "style",
type: "select",
default: "3d-model",
support: ["core"],
options: [
{ name: Locale.SdPanel.Styles.D3Model, value: "3d-model" },
{ name: Locale.SdPanel.Styles.AnalogFilm, value: "analog-film" },
{ name: Locale.SdPanel.Styles.Anime, value: "anime" },
{ name: Locale.SdPanel.Styles.Cinematic, value: "cinematic" },
{ name: Locale.SdPanel.Styles.ComicBook, value: "comic-book" },
{ name: Locale.SdPanel.Styles.DigitalArt, value: "digital-art" },
{ name: Locale.SdPanel.Styles.Enhance, value: "enhance" },
{ name: Locale.SdPanel.Styles.FantasyArt, value: "fantasy-art" },
{ name: Locale.SdPanel.Styles.Isometric, value: "isometric" },
{ name: Locale.SdPanel.Styles.LineArt, value: "line-art" },
{ name: Locale.SdPanel.Styles.LowPoly, value: "low-poly" },
{
name: Locale.SdPanel.Styles.ModelingCompound,
value: "modeling-compound",
},
{ name: Locale.SdPanel.Styles.NeonPunk, value: "neon-punk" },
{ name: Locale.SdPanel.Styles.Origami, value: "origami" },
{ name: Locale.SdPanel.Styles.Photographic, value: "photographic" },
{ name: Locale.SdPanel.Styles.PixelArt, value: "pixel-art" },
{ name: Locale.SdPanel.Styles.TileTexture, value: "tile-texture" },
],
},
{
name: "Seed",
value: "seed",
type: "number",
default: 0,
min: 0,
max: 4294967294,
},
{
name: Locale.SdPanel.OutFormat,
value: "output_format",
type: "select",
default: "png",
options: [
{ name: "PNG", value: "png" },
{ name: "JPEG", value: "jpeg" },
{ name: "WebP", value: "webp" },
],
},
];
const sdCommonParams = (model: string, data: any) => {
return params.filter((item) => {
return !(item.support && !item.support.includes(model));
});
};
export const models = [
{
name: "Stable Image Ultra",
value: "ultra",
params: (data: any) => sdCommonParams("ultra", data),
},
{
name: "Stable Image Core",
value: "core",
params: (data: any) => sdCommonParams("core", data),
},
{
name: "Stable Diffusion 3",
value: "sd3",
params: (data: any) => {
return sdCommonParams("sd3", data).filter((item) => {
return !(
data.model === "sd3-large-turbo" && item.value == "negative_prompt"
);
});
},
},
];
export function ControlParamItem(props: {
title: string;
subTitle?: string;
required?: boolean;
children?: JSX.Element | JSX.Element[];
className?: string;
}) {
return (
<div className={styles["ctrl-param-item"] + ` ${props.className || ""}`}>
<div className={styles["ctrl-param-item-header"]}>
<div className={styles["ctrl-param-item-title"]}>
<div>
{props.title}
{props.required && <span style={{ color: "red" }}>*</span>}
</div>
</div>
</div>
{props.children}
{props.subTitle && (
<div className={styles["ctrl-param-item-sub-title"]}>
{props.subTitle}
</div>
)}
</div>
);
}
export function ControlParam(props: {
columns: any[];
data: any;
onChange: (field: string, val: any) => void;
}) {
return (
<>
{props.columns?.map((item) => {
let element: null | JSX.Element;
switch (item.type) {
case "textarea":
element = (
<ControlParamItem
title={item.name}
subTitle={item.sub}
required={item.required}
>
<textarea
rows={item.rows || 3}
style={{ maxWidth: "100%", width: "100%", padding: "10px" }}
placeholder={item.placeholder}
onChange={(e) => {
props.onChange(item.value, e.currentTarget.value);
}}
value={props.data[item.value]}
></textarea>
</ControlParamItem>
);
break;
case "select":
element = (
<ControlParamItem
title={item.name}
subTitle={item.sub}
required={item.required}
>
<Select
aria-label={item.name}
value={props.data[item.value]}
onChange={(e) => {
props.onChange(item.value, e.currentTarget.value);
}}
>
{item.options.map((opt: any) => {
return (
<option value={opt.value} key={opt.value}>
{opt.name}
</option>
);
})}
</Select>
</ControlParamItem>
);
break;
case "number":
element = (
<ControlParamItem
title={item.name}
subTitle={item.sub}
required={item.required}
>
<input
aria-label={item.name}
type="number"
min={item.min}
max={item.max}
value={props.data[item.value] || 0}
onChange={(e) => {
props.onChange(item.value, parseInt(e.currentTarget.value));
}}
/>
</ControlParamItem>
);
break;
default:
element = (
<ControlParamItem
title={item.name}
subTitle={item.sub}
required={item.required}
>
<input
aria-label={item.name}
type="text"
value={props.data[item.value]}
style={{ maxWidth: "100%", width: "100%" }}
onChange={(e) => {
props.onChange(item.value, e.currentTarget.value);
}}
/>
</ControlParamItem>
);
}
return <div key={item.value}>{element}</div>;
})}
</>
);
}
export const getModelParamBasicData = (
columns: any[],
data: any,
clearText?: boolean,
) => {
const newParams: any = {};
columns.forEach((item: any) => {
if (clearText && ["text", "textarea", "number"].includes(item.type)) {
newParams[item.value] = item.default || "";
} else {
// @ts-ignore
newParams[item.value] = data[item.value] || item.default || "";
}
});
return newParams;
};
export const getParams = (model: any, params: any) => {
return models.find((m) => m.value === model.value)?.params(params) || [];
};
export function SdPanel() {
const sdStore = useSdStore();
const currentModel = sdStore.currentModel;
const setCurrentModel = sdStore.setCurrentModel;
const params = sdStore.currentParams;
const setParams = sdStore.setCurrentParams;
const handleValueChange = (field: string, val: any) => {
setParams({
...params,
[field]: val,
});
};
const handleModelChange = (model: any) => {
setCurrentModel(model);
setParams(getModelParamBasicData(model.params({}), params));
};
return (
<>
<ControlParamItem title={Locale.SdPanel.AIModel}>
<div className={styles["ai-models"]}>
{models.map((item) => {
return (
<IconButton
text={item.name}
key={item.value}
type={currentModel.value == item.value ? "primary" : null}
shadow
onClick={() => handleModelChange(item)}
/>
);
})}
</div>
</ControlParamItem>
<ControlParam
columns={getParams?.(currentModel, params) as any[]}
data={params}
onChange={handleValueChange}
></ControlParam>
</>
);
}

View File

@@ -1,140 +0,0 @@
import { IconButton } from "@/app/components/button";
import GithubIcon from "@/app/icons/github.svg";
import SDIcon from "@/app/icons/sd.svg";
import ReturnIcon from "@/app/icons/return.svg";
import HistoryIcon from "@/app/icons/history.svg";
import Locale from "@/app/locales";
import { Path, REPO_URL } from "@/app/constant";
import { useNavigate } from "react-router-dom";
import dynamic from "next/dynamic";
import {
SideBarContainer,
SideBarBody,
SideBarHeader,
SideBarTail,
useDragSideBar,
useHotKey,
} from "@/app/components/sidebar";
import { getParams, getModelParamBasicData } from "./sd-panel";
import { useSdStore } from "@/app/store/sd";
import { showToast } from "@/app/components/ui-lib";
import { useMobileScreen } from "@/app/utils";
const SdPanel = dynamic(
async () => (await import("@/app/components/sd")).SdPanel,
{
loading: () => null,
},
);
export function SideBar(props: { className?: string }) {
useHotKey();
const isMobileScreen = useMobileScreen();
const { onDragStart, shouldNarrow } = useDragSideBar();
const navigate = useNavigate();
const sdStore = useSdStore();
const currentModel = sdStore.currentModel;
const params = sdStore.currentParams;
const setParams = sdStore.setCurrentParams;
const handleSubmit = () => {
const columns = getParams?.(currentModel, params);
const reqParams: any = {};
for (let i = 0; i < columns.length; i++) {
const item = columns[i];
reqParams[item.value] = params[item.value] ?? null;
if (item.required) {
if (!reqParams[item.value]) {
showToast(Locale.SdPanel.ParamIsRequired(item.name));
return;
}
}
}
let data: any = {
model: currentModel.value,
model_name: currentModel.name,
status: "wait",
params: reqParams,
created_at: new Date().toLocaleString(),
img_data: "",
};
sdStore.sendTask(data, () => {
setParams(getModelParamBasicData(columns, params, true));
navigate(Path.SdNew);
});
};
return (
<SideBarContainer
onDragStart={onDragStart}
shouldNarrow={shouldNarrow}
{...props}
>
{isMobileScreen ? (
<div
className="window-header"
data-tauri-drag-region
style={{
paddingLeft: 0,
paddingRight: 0,
}}
>
<div className="window-actions">
<div className="window-action-button">
<IconButton
icon={<ReturnIcon />}
bordered
title={Locale.Sd.Actions.ReturnHome}
onClick={() => navigate(Path.Home)}
/>
</div>
</div>
<SDIcon width={50} height={50} />
<div className="window-actions">
<div className="window-action-button">
<IconButton
icon={<HistoryIcon />}
bordered
title={Locale.Sd.Actions.History}
onClick={() => navigate(Path.SdNew)}
/>
</div>
</div>
</div>
) : (
<SideBarHeader
title={
<IconButton
icon={<ReturnIcon />}
bordered
title={Locale.Sd.Actions.ReturnHome}
onClick={() => navigate(Path.Home)}
/>
}
logo={<SDIcon width={38} height={"100%"} />}
></SideBarHeader>
)}
<SideBarBody>
<SdPanel />
</SideBarBody>
<SideBarTail
primaryAction={
<a href={REPO_URL} target="_blank" rel="noopener noreferrer">
<IconButton icon={<GithubIcon />} shadow />
</a>
}
secondaryAction={
<IconButton
text={Locale.SdPanel.Submit}
type="primary"
shadow
onClick={handleSubmit}
></IconButton>
}
/>
</SideBarContainer>
);
}

View File

@@ -1,53 +0,0 @@
.sd-img-list{
display: flex;
flex-wrap: wrap;
justify-content: space-between;
.sd-img-item{
width: 48%;
.sd-img-item-info{
flex:1;
width: 100%;
overflow: hidden;
user-select: text;
p{
margin: 6px;
font-size: 12px;
}
.line-1{
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
}
.pre-img{
display: flex;
width: 130px;
justify-content: center;
align-items: center;
background-color: var(--second);
border-radius: 10px;
}
.img{
width: 130px;
height: 130px;
border-radius: 10px;
overflow: hidden;
cursor: pointer;
transition: all .3s;
&:hover{
opacity: .7;
}
}
&:not(:last-child){
margin-bottom: 20px;
}
}
}
@media only screen and (max-width: 600px) {
.sd-img-list{
.sd-img-item{
width: 100%;
}
}
}

View File

@@ -1,336 +0,0 @@
import chatStyles from "@/app/components/chat.module.scss";
import styles from "@/app/components/sd/sd.module.scss";
import homeStyles from "@/app/components/home.module.scss";
import { IconButton } from "@/app/components/button";
import ReturnIcon from "@/app/icons/return.svg";
import Locale from "@/app/locales";
import { Path } from "@/app/constant";
import React, { useEffect, useMemo, useRef, useState } from "react";
import {
copyToClipboard,
getMessageTextContent,
useMobileScreen,
} from "@/app/utils";
import { useNavigate, useLocation } from "react-router-dom";
import { useAppConfig } from "@/app/store";
import MinIcon from "@/app/icons/min.svg";
import MaxIcon from "@/app/icons/max.svg";
import { getClientConfig } from "@/app/config/client";
import { ChatAction } from "@/app/components/chat";
import DeleteIcon from "@/app/icons/clear.svg";
import CopyIcon from "@/app/icons/copy.svg";
import PromptIcon from "@/app/icons/prompt.svg";
import ResetIcon from "@/app/icons/reload.svg";
import { useSdStore } from "@/app/store/sd";
import LoadingIcon from "@/app/icons/three-dots.svg";
import ErrorIcon from "@/app/icons/delete.svg";
import SDIcon from "@/app/icons/sd.svg";
import { Property } from "csstype";
import {
showConfirm,
showImageModal,
showModal,
} from "@/app/components/ui-lib";
import { removeImage } from "@/app/utils/chat";
import { SideBar } from "./sd-sidebar";
import { WindowContent } from "@/app/components/home";
import { params } from "./sd-panel";
function getSdTaskStatus(item: any) {
let s: string;
let color: Property.Color | undefined = undefined;
switch (item.status) {
case "success":
s = Locale.Sd.Status.Success;
color = "green";
break;
case "error":
s = Locale.Sd.Status.Error;
color = "red";
break;
case "wait":
s = Locale.Sd.Status.Wait;
color = "yellow";
break;
case "running":
s = Locale.Sd.Status.Running;
color = "blue";
break;
default:
s = item.status.toUpperCase();
}
return (
<p className={styles["line-1"]} title={item.error} style={{ color: color }}>
<span>
{Locale.Sd.Status.Name}: {s}
</span>
{item.status === "error" && (
<span
className="clickable"
onClick={() => {
showModal({
title: Locale.Sd.Detail,
children: (
<div style={{ color: color, userSelect: "text" }}>
{item.error}
</div>
),
});
}}
>
- {item.error}
</span>
)}
</p>
);
}
export function Sd() {
const isMobileScreen = useMobileScreen();
const navigate = useNavigate();
const location = useLocation();
const clientConfig = useMemo(() => getClientConfig(), []);
const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
const config = useAppConfig();
const scrollRef = useRef<HTMLDivElement>(null);
const sdStore = useSdStore();
const [sdImages, setSdImages] = useState(sdStore.draw);
const isSd = location.pathname === Path.Sd;
useEffect(() => {
setSdImages(sdStore.draw);
}, [sdStore.currentId]);
return (
<>
<SideBar className={isSd ? homeStyles["sidebar-show"] : ""} />
<WindowContent>
<div className={chatStyles.chat} key={"1"}>
<div className="window-header" data-tauri-drag-region>
{isMobileScreen && (
<div className="window-actions">
<div className={"window-action-button"}>
<IconButton
icon={<ReturnIcon />}
bordered
title={Locale.Chat.Actions.ChatList}
onClick={() => navigate(Path.Sd)}
/>
</div>
</div>
)}
<div
className={`window-header-title ${chatStyles["chat-body-title"]}`}
>
<div className={`window-header-main-title`}>Stability AI</div>
<div className="window-header-sub-title">
{Locale.Sd.SubTitle(sdImages.length || 0)}
</div>
</div>
<div className="window-actions">
{showMaxIcon && (
<div className="window-action-button">
<IconButton
aria={Locale.Chat.Actions.FullScreen}
icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
bordered
onClick={() => {
config.update(
(config) => (config.tightBorder = !config.tightBorder),
);
}}
/>
</div>
)}
{isMobileScreen && <SDIcon width={50} height={50} />}
</div>
</div>
<div className={chatStyles["chat-body"]} ref={scrollRef}>
<div className={styles["sd-img-list"]}>
{sdImages.length > 0 ? (
sdImages.map((item: any) => {
return (
<div
key={item.id}
style={{ display: "flex" }}
className={styles["sd-img-item"]}
>
{item.status === "success" ? (
<img
className={styles["img"]}
src={item.img_data}
alt={item.id}
onClick={(e) =>
showImageModal(
item.img_data,
true,
isMobileScreen
? { width: "100%", height: "fit-content" }
: { maxWidth: "100%", maxHeight: "100%" },
isMobileScreen
? { width: "100%", height: "fit-content" }
: { width: "100%", height: "100%" },
)
}
/>
) : item.status === "error" ? (
<div className={styles["pre-img"]}>
<ErrorIcon />
</div>
) : (
<div className={styles["pre-img"]}>
<LoadingIcon />
</div>
)}
<div
style={{ marginLeft: "10px" }}
className={styles["sd-img-item-info"]}
>
<p className={styles["line-1"]}>
{Locale.SdPanel.Prompt}:{" "}
<span
className="clickable"
title={item.params.prompt}
onClick={() => {
showModal({
title: Locale.Sd.Detail,
children: (
<div style={{ userSelect: "text" }}>
{item.params.prompt}
</div>
),
});
}}
>
{item.params.prompt}
</span>
</p>
<p>
{Locale.SdPanel.AIModel}: {item.model_name}
</p>
{getSdTaskStatus(item)}
<p>{item.created_at}</p>
<div className={chatStyles["chat-message-actions"]}>
<div className={chatStyles["chat-input-actions"]}>
<ChatAction
text={Locale.Sd.Actions.Params}
icon={<PromptIcon />}
onClick={() => {
showModal({
title: Locale.Sd.GenerateParams,
children: (
<div style={{ userSelect: "text" }}>
{Object.keys(item.params).map((key) => {
let label = key;
let value = item.params[key];
switch (label) {
case "prompt":
label = Locale.SdPanel.Prompt;
break;
case "negative_prompt":
label =
Locale.SdPanel.NegativePrompt;
break;
case "aspect_ratio":
label = Locale.SdPanel.AspectRatio;
break;
case "seed":
label = "Seed";
value = value || 0;
break;
case "output_format":
label = Locale.SdPanel.OutFormat;
value = value?.toUpperCase();
break;
case "style":
label = Locale.SdPanel.ImageStyle;
value = params
.find(
(item) =>
item.value === "style",
)
?.options?.find(
(item) => item.value === value,
)?.name;
break;
default:
break;
}
return (
<div
key={key}
style={{ margin: "10px" }}
>
<strong>{label}: </strong>
{value}
</div>
);
})}
</div>
),
});
}}
/>
<ChatAction
text={Locale.Sd.Actions.Copy}
icon={<CopyIcon />}
onClick={() =>
copyToClipboard(
getMessageTextContent({
role: "user",
content: item.params.prompt,
}),
)
}
/>
<ChatAction
text={Locale.Sd.Actions.Retry}
icon={<ResetIcon />}
onClick={() => {
const reqData = {
model: item.model,
model_name: item.model_name,
status: "wait",
params: { ...item.params },
created_at: new Date().toLocaleString(),
img_data: "",
};
sdStore.sendTask(reqData);
}}
/>
<ChatAction
text={Locale.Sd.Actions.Delete}
icon={<DeleteIcon />}
onClick={async () => {
if (
await showConfirm(Locale.Sd.Danger.Delete)
) {
// remove img_data + remove item in list
removeImage(item.img_data).finally(() => {
sdStore.draw = sdImages.filter(
(i: any) => i.id !== item.id,
);
sdStore.getNextId();
});
}
}}
/>
</div>
</div>
</div>
</div>
);
})
) : (
<div>{Locale.Sd.EmptyRecord}</div>
)}
</div>
</div>
</div>
</WindowContent>
</>
);
}

View File

@@ -1,167 +0,0 @@
import { useState, useEffect, useRef, useCallback } from "react";
import { ErrorBoundary } from "./error";
import styles from "./mask.module.scss";
import { useNavigate } from "react-router-dom";
import { IconButton } from "./button";
import CloseIcon from "../icons/close.svg";
import EyeIcon from "../icons/eye.svg";
import Locale from "../locales";
import { Path } from "../constant";
import { useChatStore } from "../store";
type Item = {
id: number;
name: string;
content: string;
};
export function SearchChatPage() {
const navigate = useNavigate();
const chatStore = useChatStore();
const sessions = chatStore.sessions;
const selectSession = chatStore.selectSession;
const [searchResults, setSearchResults] = useState<Item[]>([]);
const previousValueRef = useRef<string>("");
const searchInputRef = useRef<HTMLInputElement>(null);
const doSearch = useCallback((text: string) => {
const lowerCaseText = text.toLowerCase();
const results: Item[] = [];
sessions.forEach((session, index) => {
const fullTextContents: string[] = [];
session.messages.forEach((message) => {
const content = message.content as string;
if (!content.toLowerCase || content === "") return;
const lowerCaseContent = content.toLowerCase();
// full text search
let pos = lowerCaseContent.indexOf(lowerCaseText);
while (pos !== -1) {
const start = Math.max(0, pos - 35);
const end = Math.min(content.length, pos + lowerCaseText.length + 35);
fullTextContents.push(content.substring(start, end));
pos = lowerCaseContent.indexOf(
lowerCaseText,
pos + lowerCaseText.length,
);
}
});
if (fullTextContents.length > 0) {
results.push({
id: index,
name: session.topic,
content: fullTextContents.join("... "), // concat content with...
});
}
});
// sort by length of matching content
results.sort((a, b) => b.content.length - a.content.length);
return results;
}, []);
useEffect(() => {
const intervalId = setInterval(() => {
if (searchInputRef.current) {
const currentValue = searchInputRef.current.value;
if (currentValue !== previousValueRef.current) {
if (currentValue.length > 0) {
const result = doSearch(currentValue);
setSearchResults(result);
}
previousValueRef.current = currentValue;
}
}
}, 1000);
// Cleanup the interval on component unmount
return () => clearInterval(intervalId);
}, [doSearch]);
return (
<ErrorBoundary>
<div className={styles["mask-page"]}>
{/* header */}
<div className="window-header">
<div className="window-header-title">
<div className="window-header-main-title">
{Locale.SearchChat.Page.Title}
</div>
<div className="window-header-submai-title">
{Locale.SearchChat.Page.SubTitle(searchResults.length)}
</div>
</div>
<div className="window-actions">
<div className="window-action-button">
<IconButton
icon={<CloseIcon />}
bordered
onClick={() => navigate(-1)}
/>
</div>
</div>
</div>
<div className={styles["mask-page-body"]}>
<div className={styles["mask-filter"]}>
{/**搜索输入框 */}
<input
type="text"
className={styles["search-bar"]}
placeholder={Locale.SearchChat.Page.Search}
autoFocus
ref={searchInputRef}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
const searchText = e.currentTarget.value;
if (searchText.length > 0) {
const result = doSearch(searchText);
setSearchResults(result);
}
}
}}
/>
</div>
<div>
{searchResults.map((item) => (
<div
className={styles["mask-item"]}
key={item.id}
onClick={() => {
navigate(Path.Chat);
selectSession(item.id);
}}
style={{ cursor: "pointer" }}
>
{/** 搜索匹配的文本 */}
<div className={styles["mask-header"]}>
<div className={styles["mask-title"]}>
<div className={styles["mask-name"]}>{item.name}</div>
{item.content.slice(0, 70)}
</div>
</div>
{/** 操作按钮 */}
<div className={styles["mask-actions"]}>
<IconButton
icon={<EyeIcon />}
text={Locale.SearchChat.Item.View}
/>
</div>
</div>
))}
</div>
</div>
</div>
</ErrorBoundary>
);
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useMemo, useState, Fragment } from "react";
import { useEffect, useRef, useMemo } from "react";
import styles from "./home.module.scss";
@@ -10,8 +10,8 @@ import AddIcon from "../icons/add.svg";
import CloseIcon from "../icons/close.svg";
import DeleteIcon from "../icons/delete.svg";
import MaskIcon from "../icons/mask.svg";
import PluginIcon from "../icons/plugin.svg";
import DragIcon from "../icons/drag.svg";
import DiscoveryIcon from "../icons/discovery.svg";
import Locale from "../locales";
@@ -23,20 +23,19 @@ import {
MIN_SIDEBAR_WIDTH,
NARROW_SIDEBAR_WIDTH,
Path,
PLUGINS,
REPO_URL,
} from "../constant";
import { Link, useNavigate } from "react-router-dom";
import { isIOS, useMobileScreen } from "../utils";
import dynamic from "next/dynamic";
import { showConfirm, Selector } from "./ui-lib";
import { showConfirm, showToast } from "./ui-lib";
const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, {
loading: () => null,
});
export function useHotKey() {
function useHotKey() {
const chatStore = useChatStore();
useEffect(() => {
@@ -55,7 +54,7 @@ export function useHotKey() {
});
}
export function useDragSideBar() {
function useDragSideBar() {
const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);
const config = useAppConfig();
@@ -128,21 +127,25 @@ export function useDragSideBar() {
shouldNarrow,
};
}
export function SideBarContainer(props: {
children: React.ReactNode;
onDragStart: (e: MouseEvent) => void;
shouldNarrow: boolean;
className?: string;
}) {
export function SideBar(props: { className?: string }) {
const chatStore = useChatStore();
// drag side bar
const { onDragStart, shouldNarrow } = useDragSideBar();
const navigate = useNavigate();
const config = useAppConfig();
const isMobileScreen = useMobileScreen();
const isIOSMobile = useMemo(
() => isIOS() && isMobileScreen,
[isMobileScreen],
);
const { children, className, onDragStart, shouldNarrow } = props;
useHotKey();
return (
<div
className={`${styles.sidebar} ${className} ${
className={`${styles.sidebar} ${props.className} ${
shouldNarrow && styles["narrow-sidebar"]
}`}
style={{
@@ -150,130 +153,43 @@ export function SideBarContainer(props: {
transition: isMobileScreen && isIOSMobile ? "none" : undefined,
}}
>
{children}
<div
className={styles["sidebar-drag"]}
onPointerDown={(e) => onDragStart(e as any)}
>
<DragIcon />
</div>
</div>
);
}
export function SideBarHeader(props: {
title?: string | React.ReactNode;
subTitle?: string | React.ReactNode;
logo?: React.ReactNode;
children?: React.ReactNode;
}) {
const { title, subTitle, logo, children } = props;
return (
<Fragment>
<div className={styles["sidebar-header"]} data-tauri-drag-region>
<div className={styles["sidebar-title-container"]}>
<div className={styles["sidebar-title"]} data-tauri-drag-region>
{title}
</div>
<div className={styles["sidebar-sub-title"]}>{subTitle}</div>
<div className={styles["sidebar-title"]} data-tauri-drag-region>
NextChat
</div>
<div className={styles["sidebar-sub-title"]}>
Build your own AI assistant.
</div>
<div className={styles["sidebar-logo"] + " no-dark"}>
<ChatGptIcon />
</div>
<div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
</div>
{children}
</Fragment>
);
}
export function SideBarBody(props: {
children: React.ReactNode;
onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
}) {
const { onClick, children } = props;
return (
<div className={styles["sidebar-body"]} onClick={onClick}>
{children}
</div>
);
}
<div className={styles["sidebar-header-bar"]}>
<IconButton
icon={<MaskIcon />}
text={shouldNarrow ? undefined : Locale.Mask.Name}
className={styles["sidebar-bar-button"]}
onClick={() => {
if (config.dontShowMaskSplashScreen !== true) {
navigate(Path.NewChat, { state: { fromHome: true } });
} else {
navigate(Path.Masks, { state: { fromHome: true } });
}
}}
shadow
/>
<IconButton
icon={<PluginIcon />}
text={shouldNarrow ? undefined : Locale.Plugin.Name}
className={styles["sidebar-bar-button"]}
onClick={() => showToast(Locale.WIP)}
shadow
/>
</div>
export function SideBarTail(props: {
primaryAction?: React.ReactNode;
secondaryAction?: React.ReactNode;
}) {
const { primaryAction, secondaryAction } = props;
return (
<div className={styles["sidebar-tail"]}>
<div className={styles["sidebar-actions"]}>{primaryAction}</div>
<div className={styles["sidebar-actions"]}>{secondaryAction}</div>
</div>
);
}
export function SideBar(props: { className?: string }) {
useHotKey();
const { onDragStart, shouldNarrow } = useDragSideBar();
const [showPluginSelector, setShowPluginSelector] = useState(false);
const navigate = useNavigate();
const config = useAppConfig();
const chatStore = useChatStore();
return (
<SideBarContainer
onDragStart={onDragStart}
shouldNarrow={shouldNarrow}
{...props}
>
<SideBarHeader
title="NextChat"
subTitle="Build your own AI assistant."
logo={<ChatGptIcon />}
>
<div className={styles["sidebar-header-bar"]}>
<IconButton
icon={<MaskIcon />}
text={shouldNarrow ? undefined : Locale.Mask.Name}
className={styles["sidebar-bar-button"]}
onClick={() => {
if (config.dontShowMaskSplashScreen !== true) {
navigate(Path.NewChat, { state: { fromHome: true } });
} else {
navigate(Path.Masks, { state: { fromHome: true } });
}
}}
shadow
/>
<IconButton
icon={<DiscoveryIcon />}
text={shouldNarrow ? undefined : Locale.Discovery.Name}
className={styles["sidebar-bar-button"]}
onClick={() => setShowPluginSelector(true)}
shadow
/>
</div>
{showPluginSelector && (
<Selector
items={[
{
title: "👇 Please select the plugin you need to use",
value: "-",
disable: true,
},
...PLUGINS.map((item) => {
return {
title: item.name,
value: item.path,
};
}),
]}
onClose={() => setShowPluginSelector(false)}
onSelection={(s) => {
navigate(s[0], { state: { fromHome: true } });
}}
/>
)}
</SideBarHeader>
<SideBarBody
<div
className={styles["sidebar-body"]}
onClick={(e) => {
if (e.target === e.currentTarget) {
navigate(Path.Home);
@@ -281,41 +197,32 @@ export function SideBar(props: { className?: string }) {
}}
>
<ChatList narrow={shouldNarrow} />
</SideBarBody>
<SideBarTail
primaryAction={
<>
<div className={styles["sidebar-action"] + " " + styles.mobile}>
<IconButton
icon={<DeleteIcon />}
onClick={async () => {
if (await showConfirm(Locale.Home.DeleteChat)) {
chatStore.deleteSession(chatStore.currentSessionIndex);
}
}}
/>
</div>
<div className={styles["sidebar-action"]}>
<Link to={Path.Settings}>
<IconButton
aria={Locale.Settings.Title}
icon={<SettingsIcon />}
shadow
/>
</Link>
</div>
<div className={styles["sidebar-action"]}>
<a href={REPO_URL} target="_blank" rel="noopener noreferrer">
<IconButton
aria={Locale.Export.MessageFromChatGPT}
icon={<GithubIcon />}
shadow
/>
</a>
</div>
</>
}
secondaryAction={
</div>
<div className={styles["sidebar-tail"]}>
<div className={styles["sidebar-actions"]}>
<div className={styles["sidebar-action"] + " " + styles.mobile}>
<IconButton
icon={<DeleteIcon />}
onClick={async () => {
if (await showConfirm(Locale.Home.DeleteChat)) {
chatStore.deleteSession(chatStore.currentSessionIndex);
}
}}
/>
</div>
<div className={styles["sidebar-action"]}>
<Link to={Path.Settings}>
<IconButton icon={<SettingsIcon />} shadow />
</Link>
</div>
<div className={styles["sidebar-action"]}>
<a href={REPO_URL} target="_blank" rel="noopener noreferrer">
<IconButton icon={<GithubIcon />} shadow />
</a>
</div>
</div>
<div>
<IconButton
icon={<AddIcon />}
text={shouldNarrow ? undefined : Locale.Home.NewChat}
@@ -329,8 +236,15 @@ export function SideBar(props: { className?: string }) {
}}
shadow
/>
}
/>
</SideBarContainer>
</div>
</div>
<div
className={styles["sidebar-drag"]}
onPointerDown={(e) => onDragStart(e as any)}
>
<DragIcon />
</div>
</div>
);
}

View File

@@ -61,19 +61,6 @@
font-weight: normal;
}
}
&.vertical{
flex-direction: column;
align-items: start;
.list-header{
.list-item-title{
margin-bottom: 5px;
}
.list-item-sub-title{
margin-bottom: 2px;
}
}
}
}
.list {
@@ -304,12 +291,7 @@
justify-content: center;
z-index: 999;
.selector-item-disabled{
opacity: 0.6;
}
&-content {
min-width: 300px;
.list {
max-height: 90vh;
overflow-x: hidden;

View File

@@ -13,15 +13,7 @@ import MinIcon from "../icons/min.svg";
import Locale from "../locales";
import { createRoot } from "react-dom/client";
import React, {
CSSProperties,
HTMLProps,
MouseEvent,
useEffect,
useState,
useCallback,
useRef,
} from "react";
import React, { HTMLProps, useEffect, useState } from "react";
import { IconButton } from "./button";
export function Popover(props: {
@@ -50,21 +42,16 @@ export function Card(props: { children: JSX.Element[]; className?: string }) {
}
export function ListItem(props: {
title?: string;
subTitle?: string | JSX.Element;
title: string;
subTitle?: string;
children?: JSX.Element | JSX.Element[];
icon?: JSX.Element;
className?: string;
onClick?: (e: MouseEvent) => void;
vertical?: boolean;
onClick?: () => void;
}) {
return (
<div
className={
styles["list-item"] +
` ${props.vertical ? styles["vertical"] : ""} ` +
` ${props.className || ""}`
}
className={styles["list-item"] + ` ${props.className || ""}`}
onClick={props.onClick}
>
<div className={styles["list-header"]}>
@@ -265,10 +252,9 @@ export function Input(props: InputProps) {
);
}
export function PasswordInput(
props: HTMLProps<HTMLInputElement> & { aria?: string },
) {
export function PasswordInput(props: HTMLProps<HTMLInputElement>) {
const [visible, setVisible] = useState(false);
function changeVisibility() {
setVisible(!visible);
}
@@ -276,7 +262,6 @@ export function PasswordInput(
return (
<div className={"password-input-container"}>
<IconButton
aria={props.aria}
icon={visible ? <EyeIcon /> : <EyeOffIcon />}
onClick={changeVisibility}
className={"password-eye"}
@@ -435,25 +420,17 @@ export function showPrompt(content: any, value = "", rows = 3) {
});
}
export function showImageModal(
img: string,
defaultMax?: boolean,
style?: CSSProperties,
boxStyle?: CSSProperties,
) {
export function showImageModal(img: string) {
showModal({
title: Locale.Export.Image.Modal,
defaultMax: defaultMax,
children: (
<div style={{ display: "flex", justifyContent: "center", ...boxStyle }}>
<div>
<img
src={img}
alt="preview"
style={
style ?? {
maxWidth: "100%",
}
}
style={{
maxWidth: "100%",
}}
></img>
</div>
),
@@ -465,56 +442,27 @@ export function Selector<T>(props: {
title: string;
subTitle?: string;
value: T;
disable?: boolean;
}>;
defaultSelectedValue?: T[] | T;
defaultSelectedValue?: T;
onSelection?: (selection: T[]) => void;
onClose?: () => void;
multiple?: boolean;
}) {
const [selectedValues, setSelectedValues] = useState<T[]>(
Array.isArray(props.defaultSelectedValue)
? props.defaultSelectedValue
: props.defaultSelectedValue !== undefined
? [props.defaultSelectedValue]
: [],
);
const handleSelection = (e: MouseEvent, value: T) => {
if (props.multiple) {
e.stopPropagation();
const newSelectedValues = selectedValues.includes(value)
? selectedValues.filter((v) => v !== value)
: [...selectedValues, value];
setSelectedValues(newSelectedValues);
props.onSelection?.(newSelectedValues);
} else {
setSelectedValues([value]);
props.onSelection?.([value]);
props.onClose?.();
}
};
return (
<div className={styles["selector"]} onClick={() => props.onClose?.()}>
<div className={styles["selector-content"]}>
<List>
{props.items.map((item, i) => {
const selected = selectedValues.includes(item.value);
const selected = props.defaultSelectedValue === item.value;
return (
<ListItem
className={`${styles["selector-item"]} ${
item.disable && styles["selector-item-disabled"]
}`}
className={styles["selector-item"]}
key={i}
title={item.title}
subTitle={item.subTitle}
onClick={(e) => {
if (item.disable) {
e.stopPropagation();
} else {
handleSelection(e, item.value);
}
onClick={() => {
props.onSelection?.([item.value]);
props.onClose?.();
}}
>
{selected ? (
@@ -537,38 +485,3 @@ export function Selector<T>(props: {
</div>
);
}
export function FullScreen(props: any) {
const { children, right = 10, top = 10, ...rest } = props;
const ref = useRef<HTMLDivElement>();
const [fullScreen, setFullScreen] = useState(false);
const toggleFullscreen = useCallback(() => {
if (!document.fullscreenElement) {
ref.current?.requestFullscreen();
} else {
document.exitFullscreen();
}
}, []);
useEffect(() => {
const handleScreenChange = (e: any) => {
if (e.target === ref.current) {
setFullScreen(!!document.fullscreenElement);
}
};
document.addEventListener("fullscreenchange", handleScreenChange);
return () => {
document.removeEventListener("fullscreenchange", handleScreenChange);
};
}, []);
return (
<div ref={ref} style={{ position: "relative" }} {...rest}>
<div style={{ position: "absolute", right, top }}>
<IconButton
icon={fullScreen ? <MinIcon /> : <MaxIcon />}
onClick={toggleFullscreen}
bordered
/>
</div>
{children}
</div>
);
}

View File

@@ -1,5 +1,4 @@
import tauriConfig from "../../src-tauri/tauri.conf.json";
import { DEFAULT_INPUT_TEMPLATE } from "../constant";
export const getBuildConfig = () => {
if (typeof process === "undefined") {
@@ -39,7 +38,6 @@ export const getBuildConfig = () => {
...commitInfo,
buildMode,
isApp,
template: process.env.DEFAULT_INPUT_TEMPLATE ?? DEFAULT_INPUT_TEMPLATE,
};
};

View File

@@ -3,7 +3,7 @@ import { BuildConfig, getBuildConfig } from "./build";
export function getClientConfig() {
if (typeof document !== "undefined") {
// client side
return JSON.parse(queryMeta("config") || "{}") as BuildConfig;
return JSON.parse(queryMeta("config")) as BuildConfig;
}
if (typeof process !== "undefined") {

View File

@@ -1,5 +1,5 @@
import md5 from "spark-md5";
import { DEFAULT_MODELS, DEFAULT_GA_ID } from "../constant";
import { DEFAULT_MODELS } from "../constant";
declare global {
namespace NodeJS {
@@ -21,11 +21,7 @@ declare global {
ENABLE_BALANCE_QUERY?: string; // allow user to query balance or not
DISABLE_FAST_LINK?: string; // disallow parse settings from url or not
CUSTOM_MODELS?: string; // to control custom models
DEFAULT_MODEL?: string; // to control default model in every new chat window
// stability only
STABILITY_URL?: string;
STABILITY_API_KEY?: string;
DEFAULT_MODEL?: string; // to cnntrol default model in every new chat window
// azure only
AZURE_URL?: string; // https://{azure-url}/openai/deployments/{deploy-name}
@@ -38,41 +34,6 @@ declare global {
// google tag manager
GTM_ID?: string;
// anthropic only
ANTHROPIC_URL?: string;
ANTHROPIC_API_KEY?: string;
ANTHROPIC_API_VERSION?: string;
// baidu only
BAIDU_URL?: string;
BAIDU_API_KEY?: string;
BAIDU_SECRET_KEY?: string;
// bytedance only
BYTEDANCE_URL?: string;
BYTEDANCE_API_KEY?: string;
// alibaba only
ALIBABA_URL?: string;
ALIBABA_API_KEY?: string;
// tencent only
TENCENT_URL?: string;
TENCENT_SECRET_KEY?: string;
TENCENT_SECRET_ID?: string;
// moonshot only
MOONSHOT_URL?: string;
MOONSHOT_API_KEY?: string;
// iflytek only
IFLYTEK_URL?: string;
IFLYTEK_API_KEY?: string;
IFLYTEK_API_SECRET?: string;
// custom template for preprocessing user input
DEFAULT_INPUT_TEMPLATE?: string;
}
}
}
@@ -119,33 +80,17 @@ export const getServerSideConfig = () => {
if (disableGPT4) {
if (customModels) customModels += ",";
customModels += DEFAULT_MODELS.filter(
(m) =>
(m.name.startsWith("gpt-4") || m.name.startsWith("chatgpt-4o")) &&
!m.name.startsWith("gpt-4o-mini"),
)
customModels += DEFAULT_MODELS.filter((m) => m.name.startsWith("gpt-4"))
.map((m) => "-" + m.name)
.join(",");
if (
(defaultModel.startsWith("gpt-4") ||
defaultModel.startsWith("chatgpt-4o")) &&
!defaultModel.startsWith("gpt-4o-mini")
)
defaultModel = "";
if (defaultModel.startsWith("gpt-4")) defaultModel = "";
}
const isStability = !!process.env.STABILITY_API_KEY;
const isAzure = !!process.env.AZURE_URL;
const isGoogle = !!process.env.GOOGLE_API_KEY;
const isAnthropic = !!process.env.ANTHROPIC_API_KEY;
const isTencent = !!process.env.TENCENT_API_KEY;
const isDeepSeek = !!process.env.DEEPSEEK_API_KEY;
const isBaidu = !!process.env.BAIDU_API_KEY;
const isBytedance = !!process.env.BYTEDANCE_API_KEY;
const isAlibaba = !!process.env.ALIBABA_API_KEY;
const isMoonshot = !!process.env.MOONSHOT_API_KEY;
const isIflytek = !!process.env.IFLYTEK_API_KEY;
// const apiKeyEnvVar = process.env.OPENAI_API_KEY ?? "";
// const apiKeys = apiKeyEnvVar.split(",").map((v) => v.trim());
// const randomIndex = Math.floor(Math.random() * apiKeys.length);
@@ -155,7 +100,7 @@ export const getServerSideConfig = () => {
// );
const allowedWebDevEndpoints = (
process.env.WHITE_WEBDEV_ENDPOINTS ?? ""
process.env.WEBDEV_ENDPOINTS_WHITELIST ?? ""
).split(",");
return {
@@ -163,10 +108,6 @@ export const getServerSideConfig = () => {
apiKey: getApiKey(process.env.OPENAI_API_KEY),
openaiOrgId: process.env.OPENAI_ORG_ID,
isStability,
stabilityUrl: process.env.STABILITY_URL,
stabilityApiKey: getApiKey(process.env.STABILITY_API_KEY),
isAzure,
azureUrl: process.env.AZURE_URL,
azureApiKey: getApiKey(process.env.AZURE_API_KEY),
@@ -181,40 +122,9 @@ export const getServerSideConfig = () => {
anthropicApiVersion: process.env.ANTHROPIC_API_VERSION,
anthropicUrl: process.env.ANTHROPIC_URL,
isBaidu,
baiduUrl: process.env.BAIDU_URL,
baiduApiKey: getApiKey(process.env.BAIDU_API_KEY),
baiduSecretKey: process.env.BAIDU_SECRET_KEY,
isBytedance,
bytedanceApiKey: getApiKey(process.env.BYTEDANCE_API_KEY),
bytedanceUrl: process.env.BYTEDANCE_URL,
isAlibaba,
alibabaUrl: process.env.ALIBABA_URL,
alibabaApiKey: getApiKey(process.env.ALIBABA_API_KEY),
isTencent,
tencentUrl: process.env.TENCENT_URL,
tencentSecretKey: getApiKey(process.env.TENCENT_SECRET_KEY),
tencentSecretId: process.env.TENCENT_SECRET_ID,
isMoonshot,
moonshotUrl: process.env.MOONSHOT_URL,
moonshotApiKey: getApiKey(process.env.MOONSHOT_API_KEY),
isIflytek,
iflytekUrl: process.env.IFLYTEK_URL,
iflytekApiKey: process.env.IFLYTEK_API_KEY,
iflytekApiSecret: process.env.IFLYTEK_API_SECRET,
cloudflareAccountId: process.env.CLOUDFLARE_ACCOUNT_ID,
cloudflareKVNamespaceId: process.env.CLOUDFLARE_KV_NAMESPACE_ID,
cloudflareKVApiKey: getApiKey(process.env.CLOUDFLARE_KV_API_KEY),
cloudflareKVTTL: process.env.CLOUDFLARE_KV_TTL,
deepseekApiKey: getApiKey(process.env.DEEPSEEK_API_KEY),
gtmId: process.env.GTM_ID,
gaId: process.env.GA_ID || DEFAULT_GA_ID,
needCode: ACCESS_CODES.size > 0,
code: process.env.CODE,

View File

@@ -1,9 +1,8 @@
import path from "path";
import { Chat } from "./components/chat";
export const OWNER = "ChatGPTNextWeb";
export const OWNER = "Yidadaa";
export const REPO = "ChatGPT-Next-Web";
export const REPO_URL = `https://github.com/${OWNER}/${REPO}`;
export const PLUGINS_REPO_URL = `https://github.com/${OWNER}/NextChat-Awesome-Plugins`;
export const ISSUE_URL = `https://github.com/${OWNER}/${REPO}/issues`;
export const UPDATE_URL = `${REPO_URL}#keep-updated`;
export const RELEASE_URL = `${REPO_URL}/releases`;
@@ -11,57 +10,25 @@ export const FETCH_COMMIT_URL = `https://api.github.com/repos/${OWNER}/${REPO}/c
export const FETCH_TAG_URL = `https://api.github.com/repos/${OWNER}/${REPO}/tags?per_page=1`;
export const RUNTIME_CONFIG_DOM = "danger-runtime-config";
export const STABILITY_BASE_URL = "https://api.stability.ai";
export const DEFAULT_API_HOST = "https://api.nextchat.dev";
export const OPENAI_BASE_URL = "https://api.openai.com";
export const ANTHROPIC_BASE_URL = "https://api.anthropic.com";
export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/";
export const BAIDU_BASE_URL = "https://aip.baidubce.com";
export const BAIDU_OATUH_URL = `${BAIDU_BASE_URL}/oauth/2.0/token`;
export const BYTEDANCE_BASE_URL = "https://ark.cn-beijing.volces.com";
export const ALIBABA_BASE_URL = "https://dashscope.aliyuncs.com/api/";
export const TENCENT_BASE_URL = "https://hunyuan.tencentcloudapi.com";
export const MOONSHOT_BASE_URL = "https://api.moonshot.cn";
export const IFLYTEK_BASE_URL = "https://spark-api-open.xf-yun.com";
export const CACHE_URL_PREFIX = "/api/cache";
export const UPLOAD_URL = `${CACHE_URL_PREFIX}/upload`;
export enum Path {
Home = "/",
Chat = "/chat",
Settings = "/settings",
NewChat = "/new-chat",
Masks = "/masks",
Plugins = "/plugins",
Auth = "/auth",
Sd = "/sd",
SdNew = "/sd-new",
Artifacts = "/artifacts",
SearchChat = "/search-chat",
}
export enum ApiPath {
Cors = "",
Azure = "/api/azure",
OpenAI = "/api/openai",
Anthropic = "/api/anthropic",
Google = "/api/google",
Baidu = "/api/baidu",
ByteDance = "/api/bytedance",
Alibaba = "/api/alibaba",
Tencent = "/api/tencent",
Moonshot = "/api/moonshot",
Iflytek = "/api/iflytek",
Stability = "/api/stability",
Artifacts = "/api/artifacts",
}
export enum SlotID {
@@ -76,14 +43,12 @@ export enum FileName {
export enum StoreKey {
Chat = "chat-next-web-store",
Plugin = "chat-next-web-plugin",
Access = "access-control",
Config = "app-config",
Mask = "mask-store",
Prompt = "prompt-store",
Update = "chat-update",
Sync = "sync",
SdList = "sd-list",
}
export const DEFAULT_SIDEBAR_WIDTH = 300;
@@ -107,42 +72,16 @@ export enum ServiceProvider {
Azure = "Azure",
Google = "Google",
Anthropic = "Anthropic",
Baidu = "Baidu",
ByteDance = "ByteDance",
Alibaba = "Alibaba",
Tencent = "Tencent",
Moonshot = "Moonshot",
Stability = "Stability",
Iflytek = "Iflytek",
}
// Google API safety settings, see https://ai.google.dev/gemini-api/docs/safety-settings
// BLOCK_NONE will not block any content, and BLOCK_ONLY_HIGH will block only high-risk content.
export enum GoogleSafetySettingsThreshold {
BLOCK_NONE = "BLOCK_NONE",
BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH",
BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE",
BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE",
DeepSeek = "DeepSeek",
}
export enum ModelProvider {
Stability = "Stability",
GPT = "GPT",
GeminiPro = "GeminiPro",
Claude = "Claude",
Ernie = "Ernie",
Doubao = "Doubao",
Qwen = "Qwen",
Hunyuan = "Hunyuan",
Moonshot = "Moonshot",
Iflytek = "Iflytek",
Deepseek = "DeepSeek",
}
export const Stability = {
GeneratePath: "v2beta/stable-image/generate",
ExampleEndpoint: "https://api.stability.ai",
};
export const Anthropic = {
ChatPath: "v1/messages",
ChatPath1: "v1/complete",
@@ -152,69 +91,18 @@ export const Anthropic = {
export const OpenaiPath = {
ChatPath: "v1/chat/completions",
ImagePath: "v1/images/generations",
UsagePath: "dashboard/billing/usage",
SubsPath: "dashboard/billing/subscription",
ListModelPath: "v1/models",
};
export const Azure = {
ChatPath: (deployName: string, apiVersion: string) =>
`deployments/${deployName}/chat/completions?api-version=${apiVersion}`,
// https://<your_resource_name>.openai.azure.com/openai/deployments/<your_deployment_name>/images/generations?api-version=<api_version>
ImagePath: (deployName: string, apiVersion: string) =>
`deployments/${deployName}/images/generations?api-version=${apiVersion}`,
ExampleEndpoint: "https://{resource-url}/openai",
ExampleEndpoint: "https://{resource-url}/openai/deployments/{deploy-id}",
};
export const Google = {
ExampleEndpoint: "https://generativelanguage.googleapis.com/",
ChatPath: (modelName: string) =>
`v1beta/models/${modelName}:streamGenerateContent`,
};
export const Baidu = {
ExampleEndpoint: BAIDU_BASE_URL,
ChatPath: (modelName: string) => {
let endpoint = modelName;
if (modelName === "ernie-4.0-8k") {
endpoint = "completions_pro";
}
if (modelName === "ernie-4.0-8k-preview-0518") {
endpoint = "completions_adv_pro";
}
if (modelName === "ernie-3.5-8k") {
endpoint = "completions";
}
if (modelName === "ernie-speed-8k") {
endpoint = "ernie_speed";
}
return `rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${endpoint}`;
},
};
export const ByteDance = {
ExampleEndpoint: "https://ark.cn-beijing.volces.com/api/",
ChatPath: "api/v3/chat/completions",
};
export const Alibaba = {
ExampleEndpoint: ALIBABA_BASE_URL,
ChatPath: "v1/services/aigc/text-generation/generation",
};
export const Tencent = {
ExampleEndpoint: TENCENT_BASE_URL,
};
export const Moonshot = {
ExampleEndpoint: MOONSHOT_BASE_URL,
ChatPath: "v1/chat/completions",
};
export const Iflytek = {
ExampleEndpoint: IFLYTEK_BASE_URL,
ChatPath: "v1/chat/completions",
ChatPath: (modelName: string) => `v1beta/models/${modelName}:generateContent`,
};
export const DEFAULT_INPUT_TEMPLATE = `{{input}}`; // input / time / model / lang
@@ -235,7 +123,7 @@ Latex inline: \\(x^2\\)
Latex block: $$e=mc^2$$
`;
export const SUMMARIZE_MODEL = "gpt-4o-mini";
export const SUMMARIZE_MODEL = "gpt-3.5-turbo";
export const GEMINI_SUMMARIZE_MODEL = "gemini-pro";
export const KnowledgeCutOffDate: Record<string, string> = {
@@ -243,15 +131,7 @@ export const KnowledgeCutOffDate: Record<string, string> = {
"gpt-4-turbo": "2023-12",
"gpt-4-turbo-2024-04-09": "2023-12",
"gpt-4-turbo-preview": "2023-12",
"gpt-4o": "2023-10",
"gpt-4o-2024-05-13": "2023-10",
"gpt-4o-2024-08-06": "2023-10",
"chatgpt-4o-latest": "2023-10",
"gpt-4o-mini": "2023-10",
"gpt-4o-mini-2024-07-18": "2023-10",
"gpt-4-vision-preview": "2023-04",
"o1-mini": "2023-10",
"o1-preview": "2023-10",
// After improvements,
// it's now easier to add "KnowledgeCutOffDate" instead of stupid hardcoding it, as was done previously.
"gemini-pro": "2023-12",
@@ -260,32 +140,16 @@ export const KnowledgeCutOffDate: Record<string, string> = {
const openaiModels = [
"gpt-3.5-turbo",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo-0125",
"gpt-4",
"gpt-4-0613",
"gpt-4-32k",
"gpt-4-32k-0613",
"gpt-4-turbo",
"gpt-4-turbo-preview",
"gpt-4o",
"gpt-4o-2024-05-13",
"gpt-4o-2024-08-06",
"chatgpt-4o-latest",
"gpt-4o-mini",
"gpt-4o-mini-2024-07-18",
"gpt-4-vision-preview",
"gpt-4-turbo-2024-04-09",
"gpt-4-1106-preview",
"dall-e-3",
"o1-mini",
"o1-preview"
];
const googleModels = [
"gemini-1.0-pro",
"gemini-1.5-pro-latest",
"gemini-1.5-flash-latest",
"gemini-pro-vision",
];
@@ -296,172 +160,45 @@ const anthropicModels = [
"claude-3-sonnet-20240229",
"claude-3-opus-20240229",
"claude-3-haiku-20240307",
"claude-3-5-sonnet-20240620",
];
const baiduModels = [
"ernie-4.0-turbo-8k",
"ernie-4.0-8k",
"ernie-4.0-8k-preview",
"ernie-4.0-8k-preview-0518",
"ernie-4.0-8k-latest",
"ernie-3.5-8k",
"ernie-3.5-8k-0205",
"ernie-speed-128k",
"ernie-speed-8k",
"ernie-lite-8k",
"ernie-tiny-8k",
];
const deepseekModels = ["deepseek-chat"];
const bytedanceModels = [
"Doubao-lite-4k",
"Doubao-lite-32k",
"Doubao-lite-128k",
"Doubao-pro-4k",
"Doubao-pro-32k",
"Doubao-pro-128k",
];
const alibabaModes = [
"qwen-turbo",
"qwen-plus",
"qwen-max",
"qwen-max-0428",
"qwen-max-0403",
"qwen-max-0107",
"qwen-max-longcontext",
];
const tencentModels = [
"hunyuan-pro",
"hunyuan-standard",
"hunyuan-lite",
"hunyuan-role",
"hunyuan-functioncall",
"hunyuan-code",
"hunyuan-vision",
];
const moonshotModes = ["moonshot-v1-8k", "moonshot-v1-32k", "moonshot-v1-128k"];
const iflytekModels = [
"general",
"generalv3",
"pro-128k",
"generalv3.5",
"4.0Ultra",
];
let seq = 1000; // 内置的模型序号生成器从1000开始
export const DEFAULT_MODELS = [
...openaiModels.map((name) => ({
name,
available: true,
sorted: seq++, // Global sequence sort(index)
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
sorted: 1, // 这里是固定的,确保顺序与之前内置的版本一致
},
})),
...openaiModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "azure",
providerName: "Azure",
providerType: "azure",
sorted: 2,
},
})),
...googleModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "google",
providerName: "Google",
providerType: "google",
sorted: 3,
},
})),
...anthropicModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "anthropic",
providerName: "Anthropic",
providerType: "anthropic",
sorted: 4,
},
})),
...baiduModels.map((name) => ({
...deepseekModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "baidu",
providerName: "Baidu",
providerType: "baidu",
sorted: 5,
},
})),
...bytedanceModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "bytedance",
providerName: "ByteDance",
providerType: "bytedance",
sorted: 6,
},
})),
...alibabaModes.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "alibaba",
providerName: "Alibaba",
providerType: "alibaba",
sorted: 7,
},
})),
...tencentModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "tencent",
providerName: "Tencent",
providerType: "tencent",
sorted: 8,
},
})),
...moonshotModes.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "moonshot",
providerName: "Moonshot",
providerType: "moonshot",
sorted: 9,
},
})),
...iflytekModels.map((name) => ({
name,
available: true,
sorted: seq++,
provider: {
id: "iflytek",
providerName: "Iflytek",
providerType: "iflytek",
sorted: 10,
id: "deepseek",
providerName: "DeepSeek",
providerType: "deepseek",
},
})),
] as const;
@@ -475,16 +212,8 @@ export const internalAllowedWebDavEndpoints = [
"https://dav.dropdav.com/",
"https://dav.box.com/dav",
"https://nanao.teracloud.jp/dav/",
"https://bora.teracloud.jp/dav/",
"https://webdav.4shared.com/",
"https://dav.idrivesync.com",
"https://webdav.yandex.com",
"https://app.koofr.net/dav/Koofr",
];
export const DEFAULT_GA_ID = "G-89WN60ZK2E";
export const PLUGINS = [
{ name: "Plugins", path: Path.Plugins },
{ name: "Stable Diffusion", path: Path.Sd },
{ name: "Search Chat", path: Path.SearchChat },
];

8
app/global.d.ts vendored
View File

@@ -21,16 +21,10 @@ declare interface Window {
writeBinaryFile(path: string, data: Uint8Array): Promise<void>;
writeTextFile(path: string, data: string): Promise<void>;
};
notification: {
notification:{
requestPermission(): Promise<Permission>;
isPermissionGranted(): Promise<boolean>;
sendNotification(options: string | Options): void;
};
http: {
fetch<T>(
url: string,
options?: Record<string, unknown>,
): Promise<Response<T>>;
};
};
}

View File

@@ -1,7 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1.2rem" height="1.2rem" viewBox="0 0 24 24">
<g fill="none" stroke="black" stroke-linecap="round" stroke-linejoin="round" stroke-width="2">
<circle cx="12" cy="12" r="9" />
<path
d="M11.307 9.739L15 9l-.739 3.693a2 2 0 0 1-1.568 1.569L9 15l.739-3.693a2 2 0 0 1 1.568-1.568" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 371 B

View File

@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#333" class="bi bi-badge-hd" viewBox="0 0 16 16">
<path d="M7.396 11V5.001H6.209v2.44H3.687V5H2.5v6h1.187V8.43h2.522V11zM8.5 5.001V11h2.188c1.811 0 2.685-1.107 2.685-3.015 0-1.894-.86-2.984-2.684-2.984zm1.187.967h.843c1.112 0 1.622.686 1.622 2.04 0 1.353-.505 2.02-1.622 2.02h-.843z"/>
<path d="M14 3a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zM2 2a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2z"/>
</svg>

Before

Width:  |  Height:  |  Size: 514 B

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg width="16" height="16" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M5.81836 6.72729V14H13.0911" stroke="#333" stroke-width="4" stroke-linecap="round"
stroke-linejoin="round" />
<path
d="M4 24C4 35.0457 12.9543 44 24 44V44C35.0457 44 44 35.0457 44 24C44 12.9543 35.0457 4 24 4C16.598 4 10.1351 8.02111 6.67677 13.9981"
stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
<path d="M24.005 12L24.0038 24.0088L32.4832 32.4882" stroke="#333" stroke-width="4"
stroke-linecap="round" stroke-linejoin="round" />
</svg>

Before

Width:  |  Height:  |  Size: 660 B

View File

@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#333" class="bi bi-palette" viewBox="0 0 16 16">
<path d="M8 5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3m4 3a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3M5.5 7a1.5 1.5 0 1 1-3 0 1.5 1.5 0 0 1 3 0m.5 6a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3"/>
<path d="M16 8c0 3.15-1.866 2.585-3.567 2.07C11.42 9.763 10.465 9.473 10 10c-.603.683-.475 1.819-.351 2.92C9.826 14.495 9.996 16 8 16a8 8 0 1 1 8-8m-8 7c.611 0 .654-.171.655-.176.078-.146.124-.464.07-1.119-.014-.168-.037-.37-.061-.591-.052-.464-.112-1.005-.118-1.462-.01-.707.083-1.61.704-2.314.369-.417.845-.578 1.272-.618.404-.038.812.026 1.16.104.343.077.702.186 1.025.284l.028.008c.346.105.658.199.953.266.653.148.904.083.991.024C14.717 9.38 15 9.161 15 8a7 7 0 1 0-7 7"/>
</svg>

Before

Width:  |  Height:  |  Size: 781 B

View File

@@ -1,12 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1.21em" height="1em" viewBox="0 0 256 213">
<defs>
<linearGradient id="logosStabilityAiIcon0" x1="50%" x2="50%" y1="0%" y2="100%">
<stop offset="0%" stop-color="#9d39ff" />
<stop offset="100%" stop-color="#a380ff" />
</linearGradient>
</defs>
<path fill="url(#logosStabilityAiIcon0)"
d="M72.418 212.45c49.478 0 81.658-26.205 81.658-65.626c0-30.572-19.572-49.998-54.569-58.043l-22.469-6.74c-19.71-4.424-31.215-9.738-28.505-23.312c2.255-11.292 9.002-17.667 24.69-17.667c49.872 0 68.35 17.667 68.35 17.667V16.237S123.583 0 73.223 0C25.757 0 0 24.424 0 62.236c0 30.571 17.85 48.35 54.052 56.798q3.802.95 3.885.976q8.26 2.556 22.293 6.755c18.504 4.425 23.262 9.121 23.262 23.2c0 12.872-13.374 20.19-31.074 20.19C21.432 170.154 0 144.36 0 144.36v47.078s13.402 21.01 72.418 21.01" />
<path fill="#e80000"
d="M225.442 209.266c17.515 0 30.558-12.67 30.558-29.812c0-17.515-12.67-29.813-30.558-29.813c-17.515 0-30.185 12.298-30.185 29.813s12.67 29.812 30.185 29.812" />
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg width="16" height="16" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M42 7H6C4.89543 7 4 7.89543 4 9V37C4 38.1046 4.89543 39 6 39H42C43.1046 39 44 38.1046 44 37V9C44 7.89543 43.1046 7 42 7Z" fill="none" stroke="#000" stroke-width="3" stroke-linejoin="round"/><path d="M12 19H14" stroke="#000" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/><path d="M21 19H23" stroke="#000" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/><path d="M29 19H36" stroke="#000" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/><path d="M12 28H36" stroke="#000" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/></svg>

Before

Width:  |  Height:  |  Size: 734 B

View File

@@ -1 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?><svg width="16" height="16" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M42 7H6C4.89543 7 4 7.89543 4 9V39C4 40.1046 4.89543 41 6 41H42C43.1046 41 44 40.1046 44 39V9C44 7.89543 43.1046 7 42 7Z" fill="none" stroke="#333" stroke-width="4"/><path d="M30 30V18L38 30V18" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M10 30V18L18 30V18" stroke="#333" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/><path d="M24 20V21" stroke="#333" stroke-width="4" stroke-linecap="round"/><path d="M24 27V28" stroke="#333" stroke-width="4" stroke-linecap="round"/></svg>

Before

Width:  |  Height:  |  Size: 681 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1.2rem" height="1.2rem" viewBox="0 0 24 24"><g fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></g></svg>

Before

Width:  |  Height:  |  Size: 285 B

View File

@@ -3,29 +3,28 @@ import "./styles/globals.scss";
import "./styles/markdown.scss";
import "./styles/highlight.scss";
import { getClientConfig } from "./config/client";
import type { Metadata, Viewport } from "next";
import { type Metadata } from "next";
import { SpeedInsights } from "@vercel/speed-insights/next";
import { getServerSideConfig } from "./config/server";
import { GoogleTagManager, GoogleAnalytics } from "@next/third-parties/google";
import { GoogleTagManager } from "@next/third-parties/google";
const serverConfig = getServerSideConfig();
export const metadata: Metadata = {
title: "NextChat",
description: "Your personal ChatGPT Chat Bot.",
appleWebApp: {
title: "NextChat",
statusBarStyle: "default",
viewport: {
width: "device-width",
initialScale: 1,
maximumScale: 1,
},
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
maximumScale: 1,
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "#fafafa" },
{ media: "(prefers-color-scheme: dark)", color: "#151515" },
],
appleWebApp: {
title: "NextChat",
statusBarStyle: "default",
},
};
export default function RootLayout({
@@ -37,11 +36,8 @@ export default function RootLayout({
<html lang="en">
<head>
<meta name="config" content={JSON.stringify(getClientConfig())} />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
/>
<link rel="manifest" href="/site.webmanifest" crossOrigin="use-credentials"></link>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="manifest" href="/site.webmanifest"></link>
<script src="/serviceWorkerRegister.js" defer></script>
</head>
<body>
@@ -56,11 +52,6 @@ export default function RootLayout({
<GoogleTagManager gtmId={serverConfig.gtmId} />
</>
)}
{serverConfig?.gaId && (
<>
<GoogleAnalytics gaId={serverConfig.gaId} />
</>
)}
</body>
</html>
);

View File

@@ -1,535 +1,274 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const ar: PartialLocaleType = {
WIP: "قريبًا...",
Error: {
Unauthorized: isApp
? "تم اكتشاف مفتاح API غير صالح، يرجى الذهاب إلى [الإعدادات](/#/settings) للتحقق من صحة مفتاح API."
: "كلمة المرور غير صحيحة أو فارغة، يرجى الذهاب إلى [تسجيل الدخول](/#/auth) لإدخال كلمة مرور صحيحة، أو أدخل مفتاح OpenAI API الخاص بك في [الإعدادات](/#/settings).",
Unauthorized:
"غير مصرح بالوصول، يرجى إدخال رمز الوصول [auth](/#/auth) في صفحة المصادقة.",
},
Auth: {
Title: "تحتاج إلى كلمة مرور",
Tips: "قام المشرف بتفعيل التحقق بكلمة المرور، يرجى إدخال رمز الوصول أدناه",
SubTips: "أو إدخال مفتاح API الخاص بـ OpenAI أو Google",
Input: "أدخل رمز الوصول هنا",
Title: "تحتاج إلى رمز الوصول",
Tips: "يرجى إدخال رمز الوصول أدناه",
SubTips: "أو أدخل مفتاح واجهة برمجة تطبيقات OpenAI الخاص بك",
Input: "رمز الوصول",
Confirm: "تأكيد",
Later: "في وقت لاحق",
Later: "لاحقًا",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} محادثة`,
ChatItemCount: (count: number) => `${count} رسائل`,
},
Chat: {
SubTitle: (count: number) => `إجمالي ${count} محادثة`,
EditMessage: {
Title: "تحرير سجل الرسائل",
Topic: {
Title: "موضوع الدردشة",
SubTitle: "تغيير موضوع الدردشة الحالي",
},
},
SubTitle: (count: number) => ` ${count} رسائل مع ChatGPT`,
Actions: {
ChatList: "عرض قائمة الرسائل",
CompressedHistory: "عرض التاريخ المضغوط",
Export: "تصدير سجل الدردشة",
ChatList: "الانتقال إلى قائمة الدردشة",
CompressedHistory: "ملخص ضغط ذاكرة التاريخ",
Export: "تصدير جميع الرسائل كـ Markdown",
Copy: "نسخ",
Stop: "إيقاف",
Stop: "توقف",
Retry: "إعادة المحاولة",
Pin: "تثبيت",
PinToastContent: "تم تثبيت 1 محادثة في الإشعارات المسبقة",
PinToastAction: "عرض",
Delete: "حذف",
Edit: "تحرير",
},
Commands: {
new: "دردشة جديدة",
newm: "إنشاء دردشة من القناع",
next: "الدردشة التالية",
prev: "الدردشة السابقة",
clear: "مسح السياق",
del: "حذف الدردشة",
},
InputActions: {
Stop: "إيقاف الاستجابة",
ToBottom: "الانتقال إلى الأحدث",
Stop: "توقف",
ToBottom: "إلى آخر",
Theme: {
auto: "موضوع تلقائي",
light: "الوضع الفاتح",
dark: "الوضع الداكن",
auto: "تلقائي",
light: "نمط فاتح",
dark: "نمط داكن",
},
Prompt: "الأوامر السريعة",
Masks: "جميع الأقنعة",
Clear: "مسح الدردشة",
Settings: "إعدادات الدردشة",
UploadImage: "تحميل صورة",
Prompt: "الاقتراحات",
Masks: "الأقنعة",
Clear: "مسح السياق",
Settings: "الإعدادات",
},
Rename: "إعادة تسمية الدردشة",
Typing: "يكتب…",
Typing: "كتابة...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} إرسال`;
var inputHints = ` اضغط على ${submitKey} للإرسال`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "، Shift + Enter لإدراج سطر جديد";
inputHints += "، Shift + Enter للإنشاء";
}
return inputHints + "، / لتفعيل الإكمال التلقائي، : لتفعيل الأوامر";
return inputHints + "، / للبحث في الاقتراحات";
},
Send: "إرسال",
Config: {
Reset: "مسح الذاكرة",
SaveAs: "حفظ كقناع",
Reset: "إعادة التعيين إلى الإعدادات الافتراضية",
SaveAs: "حفظ كأقنعة",
},
IsContext: "الإشعارات المسبقة",
},
Export: {
Title: "مشاركة سجل الدردشة",
Title: "تصدير الرسائل",
Copy: "نسخ الكل",
Download: حميل الملف",
Download: نزيل",
MessageFromYou: "رسالة منك",
MessageFromChatGPT: "رسالة من ChatGPT",
Share: "مشاركة على ShareGPT",
MessageFromYou: "المستخدم",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "تنسيق التصدير",
SubTitle: "يمكنك تصدير النص كـ Markdown أو صورة PNG",
Title: "صيغة التصدير",
SubTitle: "Markdown أو صورة PNG",
},
IncludeContext: {
Title: "تضمين سياق القناع",
SubTitle: "هل تريد عرض سياق القناع في الرسائل",
Title: "تضمين السياق",
SubTitle: "تصدير اقتراحات السياق في الأقنعة أم لا",
},
Steps: {
Select: "اختيار",
Select: "تحديد",
Preview: "معاينة",
},
Image: {
Toast: "يتم إنشاء لقطة الشاشة",
Modal: "اضغط مطولاً أو انقر بزر الماوس الأيمن لحفظ الصورة",
},
},
Select: {
Search: "بحث في الرسائل",
Search: "بحث",
All: "تحديد الكل",
Latest: "أحدث الرسائل",
Clear: "مسح التحديد",
Latest: "تحديد أحدث",
Clear: "مسح",
},
Memory: {
Title: "ملخص التاريخ",
EmptyContent: "محتوى المحادثة قصير جداً، لا حاجة للتلخيص",
Send: "ضغط تلقائي لسجل الدردشة كـ سياق",
Copy: "نسخ الملخص",
Reset: "[غير مستخدم]",
ResetConfirm: "تأكيد مسح ملخص التاريخ؟",
Title: "اقتراحات الذاكرة",
EmptyContent: "لا شيء حتى الآن.",
Send: "إرسال الذاكرة",
Copy: "نسخ الذاكرة",
Reset: "إعادة التعيين",
ResetConfirm:
"سيؤدي إعادة التعيين إلى مسح سجل المحادثة الحالي والذاكرة التاريخية. هل أنت متأكد أنك تريد الاستمرار؟",
},
Home: {
NewChat: "دردشة جديدة",
DeleteChat: "تأكيد حذف المحادثة المحددة؟",
DeleteToast: "تم حذف المحادثة",
Revert: "تراجع",
DeleteChat: "هل تريد تأكيد حذف المحادثة المحددة؟",
DeleteToast: "تم حذف الدردشة",
Revert: "التراجع",
},
Settings: {
Title: "الإعدادات",
SubTitle: "جميع خيارات الإعدادات",
SubTitle: "جميع الإعدادات",
Danger: {
Reset: {
Title: "إعادة تعيين جميع الإعدادات",
SubTitle: "إعادة تعيين جميع عناصر الإعدادات إلى القيم الافتراضية",
Action: "إعادة التعيين الآن",
Confirm: "تأكيد إعادة تعيين جميع الإعدادات؟",
},
Clear: {
Title: "مسح جميع البيانات",
SubTitle: "مسح جميع الدردشات وبيانات الإعدادات",
Action: "مسح الآن",
Confirm: "تأكيد مسح جميع الدردشات وبيانات الإعدادات؟",
},
},
Lang: {
Name: "Language", // انتبه: إذا كنت ترغب في إضافة ترجمة جديدة، يرجى عدم ترجمة هذه القيمة، اتركها كما هي "Language"
All: "جميع اللغات",
Name: "Language", // تنبيه: إذا كنت ترغب في إضافة ترجمة جديدة، يرجى عدم ترجمة هذه القيمة وتركها "Language"
All: "كل اللغات",
},
Avatar: "الصورة الشخصية",
Avatar: "الصورة الرمزية",
FontSize: {
Title: "حجم الخط",
SubTitle: "حجم الخط في محتوى الدردشة",
},
FontFamily: {
Title: "خط الدردشة",
SubTitle: "خط محتوى الدردشة، اتركه فارغًا لتطبيق الخط الافتراضي العالمي",
Placeholder: "اسم الخط",
SubTitle: "ضبط حجم الخط لمحتوى الدردشة",
},
InjectSystemPrompts: {
Title: "حقن الرسائل النصية النظامية",
Title: "حقن تلميحات النظام",
SubTitle:
"فرض إضافة رسالة نظامية تحاكي ChatGPT في بداية قائمة الرسائل لكل طلب",
"قم بإضافة تلميحة نظام محاكاة ChatGPT إلى بداية قائمة الرسائل المُطلَبة في كل طلب",
},
InputTemplate: {
Title: "معالجة الإدخال من قبل المستخدم",
SubTitle: "سيتم ملء آخر رسالة من المستخدم في هذا القالب",
Title: "نموذج الإدخال",
SubTitle: "سيتم ملء أحدث رسالة في هذا النموذج",
},
Update: {
Version: (x: string) => `الإصدار الحالي: ${x}`,
IsLatest: نت على أحدث إصدار",
CheckUpdate: "التحقق من التحديثات",
IsChecking: "جارٍ التحقق من التحديثات...",
FoundUpdate: (x: string) => `تم العثور على إصدار جديد: ${x}`,
GoToUpdate: "انتقل للتحديث",
Version: (x: string) => ` الإصدار: ${x}`,
IsLatest: "أحدث إصدار",
CheckUpdate: "التحقق من التحديث",
IsChecking: "جارٍ التحقق من التحديث...",
FoundUpdate: (x: string) => ` تم العثور على إصدار جديد: ${x}`,
GoToUpdate: "التحديث",
},
SendKey: "زر الإرسال",
SendKey: "مفتاح الإرسال",
Theme: "السمة",
TightBorder: "وضع بدون حدود",
TightBorder: "حدود ضيقة",
SendPreviewBubble: {
Title: "فقاعة المعاينة",
SubTitle: "معاينة محتوى Markdown في فقاعة المعاينة",
},
AutoGenerateTitle: {
Title: "توليد العنوان تلقائيًا",
SubTitle: "توليد عنوان مناسب بناءً على محتوى الدردشة",
},
Sync: {
CloudState: "بيانات السحابة",
NotSyncYet: "لم يتم التزامن بعد",
Success: "تم التزامن بنجاح",
Fail: "فشل التزامن",
Config: {
Modal: {
Title: "تكوين التزامن السحابي",
Check: "التحقق من التوفر",
},
SyncType: {
Title: "نوع التزامن",
SubTitle: "اختر خادم التزامن المفضل",
},
Proxy: {
Title: "تفعيل الوكيل",
SubTitle: "يجب تفعيل الوكيل عند التزامن عبر المتصفح لتجنب قيود CORS",
},
ProxyUrl: {
Title: "عنوان الوكيل",
SubTitle: "ينطبق فقط على الوكيل المتاح في هذا المشروع",
},
WebDav: {
Endpoint: "عنوان WebDAV",
UserName: "اسم المستخدم",
Password: "كلمة المرور",
},
UpStash: {
Endpoint: "رابط UpStash Redis REST",
UserName: "اسم النسخ الاحتياطي",
Password: "رمز UpStash Redis REST",
},
},
LocalState: "بيانات محلية",
Overview: (overview: any) => {
return `${overview.chat} دردشة، ${overview.message} رسالة، ${overview.prompt} إشعار، ${overview.mask} قناع`;
},
ImportFailed: "فشل الاستيراد",
Title: "عرض معاينة الـ Send",
SubTitle: "معاينة Markdown في فقاعة",
},
Mask: {
Splash: {
Title: "صفحة بدء القناع",
SubTitle: "عرض صفحة بدء القناع عند بدء دردشة جديدة",
},
Builtin: {
Title: "إخفاء الأقنعة المدمجة",
SubTitle: "إخفاء الأقنعة المدمجة في قائمة الأقنعة",
Title: "شاشة تظهر الأقنعة",
SubTitle: "عرض شاشة تظهر الأقنعة قبل بدء الدردشة الجديدة",
},
},
Prompt: {
Disable: {
Title: "تعطيل الإكمال التلقائي للإشعارات",
SubTitle: "استخدم / في بداية مربع النص لتفعيل الإكمال التلقائي",
Title: "تعطيل الاكتمال التلقائي",
SubTitle: "اكتب / لتشغيل الاكتمال التلقائي",
},
List: "قائمة الإشعارات المخصصة",
ListCount: (builtin: number, custom: number) =>
`مدمج ${builtin} إشعار، مخصص ${custom} إشعار`,
Edit: حرير",
List: "قائمة الاقتراحات",
ListCount: (builtin: number, custom: number) => `
${builtin} مدمجة، ${custom} تم تعريفها من قبل المستخدم`,
Edit: عديل",
Modal: {
Title: "قائمة الإشعارات",
Add: "جديد",
Search: "بحث عن إشعارات",
Title: "قائمة الاقتراحات",
Add: "إضافة واحدة",
Search: "البحث في الاقتراحات",
},
EditModal: {
Title: "تحرير الإشعارات",
Title: "تحرير الاقتراح",
},
},
HistoryCount: {
Title: "عدد الرسائل التاريخية المرفقة",
SubTitle: "عدد الرسائل التاريخية المرفقة مع كل طلب",
Title: "عدد الرسائل المرفقة",
SubTitle: "عدد الرسائل المرسلة المرفقة في كل طلب",
},
CompressThreshold: {
Title: "عتبة ضغط طول الرسائل التاريخية",
SubTitle:
"عندما يتجاوز طول الرسائل التاريخية غير المضغوطة هذه القيمة، سيتم الضغط",
Title: "حد الضغط للتاريخ",
SubTitle: "سيتم الضغط إذا تجاوزت طول الرسائل غير المضغوطة الحد المحدد",
},
Usage: {
Title: "التحقق من الرصيد",
Title: "رصيد الحساب",
SubTitle(used: any, total: any) {
return `تم استخدام $${used} هذا الشهر، إجمالي الاشتراك $${total}`;
return `تم استخدام $${used} من هذا الشهر، الاشتراك ${total}`;
},
IsChecking: "جارٍ التحقق...",
Check: "إعادة التحقق",
NoAccess: "أدخل مفتاح API أو كلمة مرور للوصول إلى الرصيد",
},
Access: {
AccessCode: {
Title: "كلمة المرور للوصول",
SubTitle: "قام المشرف بتمكين الوصول المشفر",
Placeholder: "أدخل كلمة المرور للوصول",
},
CustomEndpoint: {
Title: "واجهة مخصصة",
SubTitle: "هل تستخدم خدمة Azure أو OpenAI مخصصة",
},
Provider: {
Title: "موفر الخدمة النموذجية",
SubTitle: "التبديل بين مقدمي الخدمة المختلفين",
},
OpenAI: {
ApiKey: {
Title: "مفتاح API",
SubTitle: "استخدم مفتاح OpenAI مخصص لتجاوز قيود كلمة المرور",
Placeholder: "مفتاح OpenAI API",
},
Endpoint: {
Title: "عنوان الواجهة",
SubTitle: "يجب أن يحتوي على http(s):// بخلاف العنوان الافتراضي",
},
},
Azure: {
ApiKey: {
Title: "مفتاح الواجهة",
SubTitle: "استخدم مفتاح Azure مخصص لتجاوز قيود كلمة المرور",
Placeholder: "مفتاح Azure API",
},
Endpoint: {
Title: "عنوان الواجهة",
SubTitle: "مثال:",
},
ApiVerion: {
Title: "إصدار الواجهة (azure api version)",
SubTitle: "اختر إصدارًا معينًا",
},
},
Anthropic: {
ApiKey: {
Title: "مفتاح الواجهة",
SubTitle: "استخدم مفتاح Anthropic مخصص لتجاوز قيود كلمة المرور",
Placeholder: "مفتاح Anthropic API",
},
Endpoint: {
Title: "عنوان الواجهة",
SubTitle: "مثال:",
},
ApiVerion: {
Title: "إصدار الواجهة (claude api version)",
SubTitle: "اختر إصدار API محدد",
},
},
Google: {
ApiKey: {
Title: "مفتاح API",
SubTitle: "احصل على مفتاح API الخاص بك من Google AI",
Placeholder: "أدخل مفتاح Google AI Studio API",
},
Endpoint: {
Title: "عنوان النهاية",
SubTitle: "مثال:",
},
ApiVersion: {
Title: "إصدار API (مخصص لـ gemini-pro)",
SubTitle: "اختر إصدار API معين",
},
GoogleSafetySettings: {
Title: "مستوى تصفية الأمان من Google",
SubTitle: "تعيين مستوى تصفية المحتوى",
},
},
Baidu: {
ApiKey: {
Title: "مفتاح API",
SubTitle: "استخدم مفتاح Baidu API مخصص",
Placeholder: "مفتاح Baidu API",
},
SecretKey: {
Title: "المفتاح السري",
SubTitle: "استخدم مفتاح Baidu Secret مخصص",
Placeholder: "مفتاح Baidu Secret",
},
Endpoint: {
Title: "عنوان الواجهة",
SubTitle: "لا يدعم التخصيص، انتقل إلى .env للتكوين",
},
},
ByteDance: {
ApiKey: {
Title: "مفتاح الواجهة",
SubTitle: "استخدم مفتاح ByteDance API مخصص",
Placeholder: "مفتاح ByteDance API",
},
Endpoint: {
Title: "عنوان الواجهة",
SubTitle: "مثال:",
},
},
Alibaba: {
ApiKey: {
Title: "مفتاح الواجهة",
SubTitle: "استخدم مفتاح Alibaba Cloud API مخصص",
Placeholder: "مفتاح Alibaba Cloud API",
},
Endpoint: {
Title: "عنوان الواجهة",
SubTitle: "مثال:",
},
},
CustomModel: {
Title: "اسم النموذج المخصص",
SubTitle: "أضف خيارات نموذج مخصص، مفصولة بفواصل إنجليزية",
},
Check: "التحقق",
NoAccess: "أدخل مفتاح API للتحقق من الرصيد",
},
Model: "النموذج",
Temperature: {
Title: "العشوائية (temperature)",
SubTitle: "كلما زادت القيمة، زادت العشوائية في الردود",
},
TopP: {
Title: "عينات النواة (top_p)",
SubTitle: "مشابه للعشوائية ولكن لا تغيره مع العشوائية",
Title: "الحرارة",
SubTitle: "قيمة أكبر تجعل الإخراج أكثر عشوائية",
},
MaxTokens: {
Title: "حد أقصى للرموز لكل رد (max_tokens)",
SubTitle: "أقصى عدد للرموز في تفاعل واحد",
Title: "الحد الأقصى للرموز",
SubTitle: "الحد الأقصى لعدد الرموز المدخلة والرموز المُنشأة",
},
PresencePenalty: {
Title: جدد الموضوع (presence_penalty)",
SubTitle: "كلما زادت القيمة، زادت احتمالية التوسع في مواضيع جديدة",
Title: أثير الوجود",
SubTitle: "قيمة أكبر تزيد من احتمالية التحدث عن مواضيع جديدة",
},
FrequencyPenalty: {
Title: "عقوبة التكرار (frequency_penalty)",
SubTitle: "كلما زادت القيمة، زادت احتمالية تقليل تكرار الكلمات",
Title: "تأثير التكرار",
SubTitle: "قيمة أكبر تقلل من احتمالية تكرار نفس السطر",
},
},
Store: {
DefaultTopic: "دردشة جديدة",
BotHello: "كيف يمكنني مساعدتك؟",
Error: "حدث خطأ، يرجى المحاولة مرة أخرى لاحقًا",
DefaultTopic: "محادثة جديدة",
BotHello: "مرحبًا! كيف يمكنني مساعدتك اليوم؟",
Error: "حدث خطأ ما، يرجى المحاولة مرة أخرى في وقت لاحق.",
Prompt: {
History: (content: string) =>
"هذا ملخص للدردشة السابقة كنقطة انطلاق: " + content,
History: (content: string) => "هذا ملخص لسجل الدردشة كمراجعة: " + content,
Topic:
"استخدم أربع إلى خمس كلمات لإرجاع ملخص مختصر لهذه الجملة، بدون شرح، بدون علامات ترقيم، بدون كلمات تعبيرية، بدون نص إضافي، بدون تنسيق عريض، إذا لم يكن هناك موضوع، يرجى العودة إلى 'دردشة عامة'",
"يرجى إنشاء عنوان يتكون من أربع إلى خمس كلمات يلخص محادثتنا دون أي مقدمة أو ترقيم أو علامات ترقيم أو نقاط أو رموز إضافية. قم بإزالة علامات التنصيص المحيطة.",
Summarize:
"قم بتلخيص محتوى الدردشة باختصار، لاستخدامه كإشارة سياقية لاحقة، اجعلها في حدود 200 كلمة",
"قم بتلخيص النقاش بشكل موجز في 200 كلمة أو أقل لاستخدامه كاقتراح للسياق في المستقبل.",
},
},
Copy: {
Success: "تم الكتابة إلى الحافظة",
Failed: "فشل النسخ، يرجى منح أذونات الحافظة",
},
Download: {
Success: "تم تنزيل المحتوى إلى مجلدك.",
Failed: "فشل التنزيل.",
Success: "تم النسخ إلى الحافظة",
Failed: "فشلت عملية النسخ، يرجى منح الإذن للوصول إلى الحافظة",
},
Context: {
Toast: (x: any) => `يحتوي على ${x} إشعارات مخصصة`,
Edit: "إعدادات الدردشة الحالية",
Add: "إضافة دردشة جديدة",
Clear: "تم مسح السياق",
Revert: "استعادة السياق",
Toast: (x: any) => `مع ${x} اقتراحًا ذا سياق`,
Edit: "الاقتراحات السياقية والذاكرة",
Add: "إضافة اقتراح",
Clear: "مسح السياق",
Revert: "التراجع",
},
Plugin: {
Name: "الإضافات",
Name: "المكوّن الإضافي",
},
FineTuned: {
Sysmessage: "أنت مساعد",
},
SearchChat: {
Name: "بحث",
Page: {
Title: "البحث في سجلات الدردشة",
Search: "أدخل كلمات البحث",
NoResult: "لم يتم العثور على نتائج",
NoData: "لا توجد بيانات",
Loading: "جارٍ التحميل",
SubTitle: (count: number) => `تم العثور على ${count} نتائج`,
},
Item: {
View: "عرض",
},
Sysmessage: "أنت مساعد ي",
},
Mask: {
Name: "القناع",
Name: "الأقنعة",
Page: {
Title: "أقنعة الأدوار المخصصة",
SubTitle: (count: number) => `${count} تعريف لدور مخصص`,
Search: "بحث عن قناع الدور",
Create: "إنشاء جديد",
Title: "قالب الاقتراح",
SubTitle: (count: number) => `${count} قوالب الاقتراح`,
Search: "البحث في القوالب",
Create: "إنشاء",
},
Item: {
Info: (count: number) => `يحتوي على ${count} محادثات مخصصة`,
Info: (count: number) => `${count} اقتراحات`,
Chat: "الدردشة",
View: "عرض",
Edit: حرير",
Edit: عديل",
Delete: "حذف",
DeleteConfirm: "تأكيد الحذف؟",
},
EditModal: {
Title: (readonly: boolean) =>
`تحرير القناع المخصص ${readonly ? " (للقراءة فقط)" : ""}`,
Download: "تنزيل القناع المخصص",
Clone: "استنساخ القناع",
Title: (readonly: boolean) => `
تعديل قالب الاقتراح ${readonly ? "(للقراءة فقط)" : ""}`,
Download: "تنزيل",
Clone: "استنساخ",
},
Config: {
Avatar: "صورة الدور",
Name: "اسم الدور",
Avatar: "صورة الروبوت",
Name: "اسم الروبوت",
Sync: {
Title: "استخدام الإعدادات العالمية",
SubTitle: "هل تستخدم الدردشة الحالية الإعدادات العالمية للنموذج",
Confirm:
"ستتم الكتابة فوق الإعدادات المخصصة للدردشة الحالية تلقائيًا، تأكيد تفعيل الإعدادات العالمية؟",
Title: "استخدام الإعدادات العامة",
SubTitle: "استخدام الإعدادات العامة في هذه الدردشة",
Confirm: "تأكيد الاستبدال بالإعدادات المخصصة بالإعدادات العامة؟",
},
HideContext: {
Title: "إخفاء المحادثات المخصصة",
SubTitle: "بعد الإخفاء، لن تظهر المحادثات المخصصة في واجهة الدردشة",
},
Share: {
Title: "مشاركة هذا القناع",
SubTitle: "إنشاء رابط مباشر لهذا القناع",
Action: "نسخ الرابط",
Title: "إخفاء اقتراحات السياق",
SubTitle: "عدم عرض اقتراحات السياق في الدردشة",
},
},
},
NewChat: {
Return: "العودة",
Skip: "بدء الآن",
Skip: "ابدأ فقط",
Title: "اختيار قناع",
SubTitle: "دردشة مع الروح وراء القناع",
More: "المزيد",
NotShow: "عدم العرض مرة أخرى",
ConfirmNoShow:
"تأكيد إلغاء العرض؟ بعد الإلغاء، يمكنك إعادة تفعيله في الإعدادات في أي وقت.",
Title: "اختر قناعًا",
SubTitle: "ابدأ الآن وتفاعل مع الأفكار خلف القناع",
More: "عرض الكل",
},
URLCommand: {
Code: "تم الكشف عن رمز وصول في الرابط، هل تريد تعبئته تلقائيًا؟",
Settings: "تم الكشف عن إعدادات مسبقة في الرابط، هل تريد تعبئتها تلقائيًا؟",
ConfirmNoShow: "تأكيد تعطيله؟ يمكنك تمكينه في الإعدادات لاحقًا.",
},
UI: {
@@ -537,16 +276,9 @@ const ar: PartialLocaleType = {
Cancel: "إلغاء",
Close: "إغلاق",
Create: "إنشاء",
Edit: حرير",
Export: "تصدير",
Import: "استيراد",
Sync: "مزامنة",
Config: "تكوين",
Edit: عديل",
},
Exporter: {
Description: {
Title: "فقط الرسائل بعد مسح السياق سيتم عرضها",
},
Model: "النموذج",
Messages: "الرسائل",
Topic: "الموضوع",

View File

@@ -1,564 +1,332 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
import { PartialLocaleType } from "./index";
const bn: PartialLocaleType = {
WIP: "শীঘ্রই আসছে...",
Error: {
Unauthorized: isApp
? "অবৈধ API কী সনাক্ত করা হয়েছে, অনুগ্রহ করে [সেটিংস](/#/settings) পৃষ্ঠায় যান এবং নিশ্চিত করুন যে API কী সঠিকভাবে কনফিগার করা হয়েছে।"
: "অ্যাক্সেস পাসওয়ার্ড সঠিক নয় বা খালি, অনুগ্রহ করে [লগইন](/#/auth) পৃষ্ঠায় যান এবং সঠিক অ্যাক্সেস পাসওয়ার্ড প্রবেশ করান, অথবা [সেটিংস](/#/settings) পৃষ্ঠায় আপনার OpenAI API কী প্রবেশ করান।",
Unauthorized:
"অননুমোদিত অ্যাক্সেস, অনুগ্রহ করে [অথোরাইজশন](/#/auth) পৃষ্ঠায় অ্যাক্সেস কোড ইনপুট করুন।",
},
Auth: {
Title: "পাসওয়ার্ড প্রয়োজন",
Tips: "অ্যাডমিন পাসওয়ার্ড প্রমাণীকরণ চালু করেছেন, নিচে অ্যাক্সেস কোড প্রবেশ করুন",
SubTips: "অথবা আপনার OpenAI অথবা Google API কী প্রবেশ করন",
Input: "এখানে অ্যাক্সেস কোড লিখুন",
Title: "একটি অ্যাক্সেস কোড প্রয়োজন",
Tips: "নীচে অ্যাক্সেস কোড ইনপুট করুন",
SubTips: "অথবা আপনার OpenAI API কী প্রবেশ করন",
Input: "অ্যাক্সেস কোড",
Confirm: "নিশ্চিত করুন",
Later: "পরে বলুন",
Later: "পরে",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} টি চ্যাট`,
ChatItemCount: (count: number) => `${count} টি বার্তা`,
},
Chat: {
SubTitle: (count: number) => `মোট ${count} টি চ্যাট`,
EditMessage: {
Title: "বার্তাগুলি সম্পাদনা করুন",
Topic: {
Title: "চ্যাটের বিষয়",
SubTitle: "বর্তমান চ্যাটের বিষয় পরিবর্তন করুন",
},
},
SubTitle: (count: number) => `${count} টি বার্তা`,
Actions: {
ChatList: "বার্তা তালিকা দেখুন",
CompressedHistory: "সংকুচিত ইতিহাস দেখুন",
Export: "চ্যাট ইতিহাস রপ্তান করুন",
Copy: "অনুলিপি করুন",
Stop: "থামান",
ChatList: "চ্যাট তালিকায় যান",
CompressedHistory: "সংক্ষিপ্ত ইতিহাস মেমোরি প্রম্পট",
Export: "সমস্ত বার্তা মার্কডাউন হিসাবে রপ্তানি করুন",
Copy: "কপি",
Stop: "বন্ধ করুন",
Retry: "পুনরায় চেষ্টা করুন",
Pin: "পিন করুন",
PinToastContent: "1 টি চ্যাট পূর্বনির্ধারিত প্রম্পটে পিন করা হয়েছে",
PinToastContent: "পিন করা হয়েছে ২টি বার্তা প্রম্পটে",
PinToastAction: "দেখুন",
Delete: "মুছে ফেলুন",
Edit: "সম্পাদন করুন",
Edit: "সম্পাদন করুন",
},
Commands: {
new: "নতুন চ্যাট",
newm: "মাস্ক থেকে নতুন চ্যাট",
new: "নতুন চ্যাট শুরু করুন",
newm: "মাস্ক সহ নতুন চ্যাট শুরু করুন",
next: "পরবর্তী চ্যাট",
prev: "পূর্ববর্তী চ্যাট",
clear: "প্রসঙ্গ পরিষ্কার করুন",
del: "চ্যাট মুছে ফেলুন",
clear: "সংশ্লিষ্টতাবদ্ধকরণ পরিষ্কার করুন",
del: "চ্যাট মুছুন",
},
InputActions: {
Stop: "প্রতিক্রিয়া থামান",
ToBottom: "সর্বশেষে স্ক্রোল করুন",
Stop: "বন্ধ করুন",
ToBottom: "সর্বশেষতম দিকে",
Theme: {
auto: "স্বয়ংক্রিয় থিম",
light: "আলোর মোড",
dark: "অন্ধকার মোড",
auto: "অটো",
light: "হালকা থিম",
dark: "ডার্ক থিম",
},
Prompt: "সংক্ষিপ্ত নির্দেশনা",
Masks: "সমস্ত মাস্ক",
Clear: "চ্যাট পরিষ্কার করুন",
Settings: "চ্যাট সেটিংস",
UploadImage: "চিত্র আপলোড করুন",
Prompt: "প্রম্পটগুলিতে",
Masks: "মাস্কগুলি",
Clear: "সংশ্লিষ্টতাবদ্ধকরণ পরিষ্কার করুন",
Settings: "সেটিংস",
},
Rename: "চ্যাট নাম পরিবর্তন করুন",
Typing: "লিখছে…",
Rename: "চ্যাট পুনঃনামকরণ করুন",
Typing: "টাইপিং...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} পাঠান`;
var inputHints = `${submitKey} to send`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter নতুন লাইন";
inputHints += ", Shift + Enter to wrap";
}
return inputHints + "/ পূর্ণতা সক্রিয় করুন,: কমান্ড সক্রিয় করুন";
return inputHints + ", / to search prompts, : to use commands";
},
Send: "পাঠান",
Send: "প্রেরণ করুন",
Config: {
Reset: "মেমরি মুছে ফেলুন",
Reset: "ডিফল্টে রিসেট করুন",
SaveAs: "মাস্ক হিসাবে সংরক্ষণ করুন",
},
IsContext: "পূর্বনির্ধারিত প্রম্পট",
},
Export: {
Title: "চ্যাট ইতিহাস শেয়ার করুন",
Copy: "সবকিছু কপি করুন",
Download: "ফাইল ডাউনলোড করুন",
Share: "ShareGPT তে শেয়ার করুন",
MessageFromYou: "্যবহারকারী",
MessageFromChatGPT: "ChatGPT",
Title: "বার্তা রপ্তানিকরণ",
Copy: "সমস্তটি কপি করুন",
Download: "ডাউনলোড করুন",
MessageFromYou: "আপনার বার্তা",
MessageFromChatGPT: "্যাটজিপিটির বার্তা",
Share: "শেয়ার করুন শেয়ারজিপিটি তে",
Format: {
Title: "রপ্তানি ফরম্যাট",
SubTitle: "Markdown টেক্সট বা PNG চিত্র রপ্তানি করা যাবে",
Title: "রপ্তানি ফরম্যাট",
SubTitle: "মার্কডাউন বা পিএনজি চিত্র",
},
IncludeContext: {
Title: "মাস্ক প্রসঙ্গ অন্তর্ভুক্ত করুন",
SubTitle: "বার্তায় মাস্ক প্রসঙ্গ প্রদর্শন করা হবে কি না",
Title: "মাস্ক অন্তর্ভুক্ত করুন",
SubTitle: "মাস্কগুলি সংরক্ষণ করবেন না কি",
},
Steps: {
Select: "নির্বাচন করুন",
Preview: "পূর্বরূপ দেখুন",
},
Image: {
Toast: "স্ক্রীনশট তৈরি করা হচ্ছে",
Modal: "ছবি সংরক্ষণ করতে দীর্ঘ প্রেস করুন অথবা রাইট ক্লিক করুন",
Preview: "প্রিভিউ করুন",
},
},
Select: {
Search: "বার্তা অনুসন্ধান করুন",
All: "সবকিছু নির্বাচন করুন",
Latest: "সর্বশেষ কিছু",
Clear: "নির্বাচন পরিষ্কার করুন",
Search: "অনুসন্ধান করুন",
All: "সমস্তটি নির্বাচন করুন",
Latest: "সর্বশেষতমটি নির্বাচন করুন",
Clear: "পরিষ্কার করুন",
},
Memory: {
Title: "ইতিহাস সারাংশ",
EmptyContent: "চ্যাটের বিষয়বস্তু খুব সংক্ষিপ্ত, সারাংশ প্রয়োজন নেই",
Send: "অটোমেটিক চ্যাট ইতিহাস সংকুচিত করুন এবং প্রসঙ্গ হিসেবে পাঠান",
Copy: "সারাংশ কপি করুন",
Reset: "[unused]",
ResetConfirm: "ইতিহাস সারাংশ মুছে ফেলার নিশ্চিত করুন?",
Title: "মেমোরি প্রম্পট",
EmptyContent: "এখনও কিছুই নেই",
Send: "মেমোরি প্রেরণ করুন",
Copy: "মেমোরি কপি করুন",
Reset: "পুনরায় নিশ্চিত করুন",
ResetConfirm:
"রিসেট করলে বর্তমান চ্যাট ইতিহাস এবং ঐতিহাসিক মেমোরি মুছে যাবে। পুনরায় নির্দিষ্ট করতে চান তা নিশ্চিত করতে চান?",
},
Home: {
NewChat: "নতুন চ্যাট",
DeleteChat: "নির্বাচিত চ্যাট মুছে ফেলার নিশ্চিত করুন?",
DeleteToast: "চ্যাট মুছে ফেলা হয়েছে",
Revert: "পূর্বাবস্থায় ফেরান",
DeleteChat: "নির্বাচিত সংলাপটি মুছতে নিশ্চিত করুন?",
DeleteToast: "চ্যাটটি মুছেছে",
Revert: "পুনরায়",
},
Settings: {
Title: "সেটিংস",
SubTitle: "সমস্ত সেটিংস অপশন",
SubTitle: "সমস্ত সেটিংস",
Danger: {
Reset: {
Title: "সমস্ত সেটিংস পুনরায় সেট করুন",
SubTitle: "সমস্ত সেটিংস বিকল্পগুলিকে ডিফল্ট মানে পুনরায় সেট করুন",
Action: "এখনই পুনরায় সেট করুন",
Confirm: "সমস্ত সেটিংস পুনরায় সেট করার নিশ্চিত করুন?",
Title: "সমস্ত সেটিংস পুনঃনির্দেশ দিন",
SubTitle: "সকল সেটিংস ডিফল্টে পুনঃনির্দেশ দিতে",
Action: "পুনঃনির্দেশ দিন",
Confirm: "সমস্ত সেটিংস ডিফল্টে পুনঃনির্দেশ করতে নিশ্চিত করতে?",
},
Clear: {
Title: "সমস্ত তথ্য মুছে ফেলুন",
SubTitle: "সমস্ত চ্যাট এবং সেটিংস ডেটা মুছে ফেলুন",
Action: "এখনই মুছে ফেলুন",
Confirm: "সমস্ত চ্যাট এবং সেটিংস ডেটা মুছে ফেলানোর নিশ্চিত করুন?",
Title: "সমস্ত তথ্য মুছুন",
SubTitle: "সমস্ত বার্তা এবং সেটিংস মুছুন",
Action: "মুছুন",
Confirm: "সমস্ত বার্তা এবং সেটিংস মুছে ফেলতে নিশ্চিত করতে?",
},
},
Lang: {
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
Name: "বাংলা", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "সমস্ত ভাষা",
},
Avatar: "অভিনেতা",
Avatar: "অতা",
FontSize: {
Title: "ফন্ট সাইজ",
SubTitle: "চ্যাট কনটেন্টের ফন্ট সাইজ",
},
FontFamily: {
Title: "চ্যাট ফন্ট",
SubTitle:
"চ্যাট সামগ্রীর ফন্ট, বিশ্বব্যাপী ডিফল্ট ফন্ট প্রয়োগ করতে খালি রাখুন",
Placeholder: "ফন্টের নাম",
SubTitle: "চ্যাট সামগ্রীর ফন্ট সাইজ সংশোধন করুন",
},
InjectSystemPrompts: {
Title: "সিস্টেম-লেভেল প্রম্পট যোগ করুন",
Title: "حقن تلميحات النظام",
SubTitle:
"প্রত্যেক বার্তায় একটি সিস্টেম প্রম্পট যোগ করুন যা ChatGPT এর অনুকরণ করবে",
"قم بإضافة تلميحة نظام محاكاة ChatGPT إلى بداية قائمة الرسائل المُطلَبة في كل طلب",
},
InputTemplate: {
Title: "ব্যবহারকারীর ইনপুট প্রিপ্রসেসিং",
SubTitle: "ব্যবহারকারীর সর্বশেষ বার্তা এই টেমপ্লেটে পূরণ করা হবে",
Title: "ইনপুট টেমপ্লেট",
SubTitle: "নতুনতম বার্তা এই টেমপ্লেটে পূরণ হবে",
},
Update: {
Version: (x: string) => `বর্তমান সংস্করণ: ${x}`,
IsLatest: "এটি সর্বশেষ সংস্করণ",
CheckUpdate: "আপডেট পরীক্ষা করুন",
IsChecking: "আপডেট পরীক্ষা করা হচ্ছে...",
FoundUpdate: (x: string) => `নতুন সংস্করণ পাওয়া গিয়েছে: ${x}`,
GoToUpdate: "আপডেট করতে যান",
Version: (x: string) => `Version: ${x}`,
IsLatest: "Latest version",
CheckUpdate: "Check Update",
IsChecking: "Checking update...",
FoundUpdate: (x: string) => `Found new version: ${x}`,
GoToUpdate: "Update",
},
SendKey: "পাঠানোর কী",
SendKey: "প্রেরণ চাবি",
Theme: "থিম",
TightBorder: "বর্ডার-বিহীন মোড",
TightBorder: "সঙ্গতি সীমা",
SendPreviewBubble: {
Title: "প্রিভিউ বুবু",
SubTitle: "প্রিভিউ বুবুMarkdown কনটেন্ট প্রিভিউ করুন",
},
AutoGenerateTitle: {
Title: "স্বয়ংক্রিয় শিরোনাম জেনারেশন",
SubTitle: "চ্যাট কনটেন্টের ভিত্তিতে উপযুক্ত শিরোনাম তৈরি করুন",
},
Sync: {
CloudState: "ক্লাউড ডেটা",
NotSyncYet: "এখনো সিঙ্ক করা হয়নি",
Success: "সিঙ্ক সফল",
Fail: "সিঙ্ক ব্যর্থ",
Config: {
Modal: {
Title: "ক্লাউড সিঙ্ক কনফিগার করুন",
Check: "পরীক্ষা করুন",
},
SyncType: {
Title: "সিঙ্ক টাইপ",
SubTitle: "পছন্দসই সিঙ্ক সার্ভার নির্বাচন করুন",
},
Proxy: {
Title: "প্রক্সি সক্রিয় করুন",
SubTitle:
"ব্রাউজারে সিঙ্ক করার সময়, ক্রস-অরিজিন সীমাবদ্ধতা এড়াতে প্রক্সি সক্রিয় করতে হবে",
},
ProxyUrl: {
Title: "প্রক্সি ঠিকানা",
SubTitle:
"এটি শুধুমাত্র প্রকল্পের সাথে সরবরাহিত ক্রস-অরিজিন প্রক্সির জন্য প্রযোজ্য",
},
WebDav: {
Endpoint: "WebDAV ঠিকানা",
UserName: "ব্যবহারকারীর নাম",
Password: "পাসওয়ার্ড",
},
UpStash: {
Endpoint: "UpStash Redis REST URL",
UserName: "ব্যাকআপ নাম",
Password: "UpStash Redis REST টোকেন",
},
},
LocalState: "স্থানীয় ডেটা",
Overview: (overview: any) => {
return `${overview.chat} বার চ্যাট, ${overview.message} বার্তা, ${overview.prompt} প্রম্পট, ${overview.mask} মাস্ক`;
},
ImportFailed: "আমদানি ব্যর্থ",
Title: "প্রিভিউ বুবুল প্রেরণ করুন",
SubTitle: "বুবুমার্কডাউন প্রিভিউ করুন",
},
Mask: {
Splash: {
Title: "মাস্ক লঞ্চ পেজ",
SubTitle: "নতুন চ্যাট শুরু করার সময় মাস্ক লঞ্চ পেজ প্রদর্শন করুন",
Title: "মাস্ক স্প্ল্যাশ স্ক্রিন",
SubTitle:
"নতুন চ্যাট শুরু করার আগে মাস্ক স্প্ল্যাশ স্ক্রিন প্রদর্শন করুন",
},
Builtin: {
Title: "ইনবিল্ট মাস্ক লুকান",
SubTitle: "সমস্ত মাস্ক তালিকায় ইনবিল্ট মাস্ক লুকান",
Title: "মূলত মাস্ক গোপন করুন",
SubTitle: "মাস্ক তালিকা থেকে মূলত মাস্কগুলি লুকান",
},
},
Prompt: {
Disable: {
Title: "প্রম্পট অটো-কমপ্লিশন নিষ্ক্রিয় করুন",
SubTitle: "ইনপুট বক্সের শুরুতে / টাইপ করলে অটো-কমপ্লিশন সক্রিয় হবে",
Title: "অটো-সম্পূর্ণতা নিষ্ক্রিয় করুন",
SubTitle: "অটো-সম্পূর্ণতা চালু করতে / ইনপুট করুন",
},
List: "স্বনির্ধারিত প্রম্পট তালিকা",
List: "প্রম্পট তালিকা",
ListCount: (builtin: number, custom: number) =>
`ইনবিল্ট ${builtin} টি, ব্যবহারকারী সংজ্ঞায়িত ${custom} টি`,
Edit: "সম্পাদন করুন",
`${builtin} built-in, ${custom} user-defined`,
Edit: "সম্পাদন করুন",
Modal: {
Title: "প্রম্পট তালিকা",
Add: "নতুন করুন",
Search: "প্রম্পট অনুসন্ধান করুন",
Add: "একটি যোগ করুন",
Search: "সন্ধান প্রম্পট",
},
EditModal: {
Title: "প্রম্পট সম্পাদন করুন",
Title: "সম্পাদন করুন প্রম্পট",
},
},
HistoryCount: {
Title: "সংযুক্ত ইতিহাস বার্তা সংখ্যা",
SubTitle: "প্রতিটি অনুরোধে সংযুক্ত ইতিহাস বার্তার সংখ্যা",
Title: "সংযুক্ত বার্তা সংখ্যা",
SubTitle: "প্রতি অনুরোধে প্রেরণ করা গেলে প্রেরণ করা হবে",
},
CompressThreshold: {
Title: "ইতিহাস বার্তা দৈর্ঘ্য সংকুচিত থ্রেশহোল্ড",
Title: "ইতিহাস সঙ্কুচিত করার সীমা",
SubTitle:
"যখন সংকুচিত ইতিহাস বার্তা এই মান ছাড়িয়ে যায়, তখন সংকুচিত করা হবে",
"নকুল বার্তা দৈর্ঘ্য সীমা অতিক্রান্ত হলে ঐ বার্তাটি সঙ্কুচিত হবে",
},
Usage: {
Title: "ব্যালেন্স চেক",
Title: "একাউন্ট ব্যালেন্স",
SubTitle(used: any, total: any) {
return `এই মাসে ব্যবহৃত $${used}, সাবস্ক্রিপশন মোট $${total}`;
return `এই মাসে ব্যবহৃত $${used}, সাবস্ক্রিপশন $${total}`;
},
IsChecking: "পরীক্ষা করা হচ্ছে",
Check: "পুনরায় পরীক্ষা করুন",
NoAccess: "ব্যালেন্স দেখতে API কী অথবা অ্যাক্সেস পাসওয়ার্ড প্রবেশ করুন",
IsChecking: "চেক করা হচ্ছে...",
Check: "চেক",
NoAccess: "ব্যালেন্স চেক করতে অ্যাপি কী ইনপুট করুন",
},
Access: {
AccessCode: {
Title: "অ্যাক্সেস পাসওয়ার্ড",
SubTitle: "অ্যাডমিন এনক্রিপ্টেড অ্যাক্সেস সক্রিয় করেছেন",
Placeholder: "অ্যাক্সেস পাসওয়ার্ড প্রবেশ করুন",
},
CustomEndpoint: {
Title: "স্বনির্ধারিত ইন্টারফেস",
SubTitle: "স্বনির্ধারিত Azure বা OpenAI সার্ভিস ব্যবহার করবেন কি?",
},
Provider: {
Title: "মডেল পরিষেবা প্রদানকারী",
SubTitle: "বিভিন্ন পরিষেবা প্রদানকারীতে স্যুইচ করুন",
},
OpenAI: {
ApiKey: {
Title: "API কী",
SubTitle:
"পাসওয়ার্ড অ্যাক্সেস সীমাবদ্ধতা এড়াতে স্বনির্ধারিত OpenAI কী ব্যবহার করুন",
Placeholder: "OpenAI API কী",
},
Endpoint: {
Title: "ইন্টারফেস ঠিকানা",
SubTitle: "ডিফল্ট ঠিকানা বাদে, http(s):// অন্তর্ভুক্ত করতে হবে",
},
},
Azure: {
ApiKey: {
Title: "ইন্টারফেস কী",
SubTitle:
"পাসওয়ার্ড অ্যাক্সেস সীমাবদ্ধতা এড়াতে স্বনির্ধারিত Azure কী ব্যবহার করুন",
Placeholder: "Azure API কী",
},
Endpoint: {
Title: "ইন্টারফেস ঠিকানা",
SubTitle: "উদাহরণ:",
},
ApiVerion: {
Title: "ইন্টারফেস সংস্করণ (azure api version)",
SubTitle: "নির্দিষ্ট সংস্করণ নির্বাচন করুন",
},
},
Anthropic: {
ApiKey: {
Title: "ইন্টারফেস কী",
SubTitle:
"পাসওয়ার্ড অ্যাক্সেস সীমাবদ্ধতা এড়াতে স্বনির্ধারিত Anthropic কী ব্যবহার করুন",
Placeholder: "Anthropic API কী",
},
Endpoint: {
Title: "ইন্টারফেস ঠিকানা",
SubTitle: "উদাহরণ:",
},
ApiVerion: {
Title: "ইন্টারফেস সংস্করণ (claude api version)",
SubTitle: "নির্দিষ্ট API সংস্করণ প্রবেশ করুন",
},
},
Google: {
ApiKey: {
Title: "API কী",
SubTitle: "Google AI থেকে আপনার API কী পান",
Placeholder: "আপনার Google AI Studio API কী প্রবেশ করুন",
},
Endpoint: {
Title: "টার্মিনাল ঠিকানা",
SubTitle: "উদাহরণ:",
},
ApiVersion: {
Title: "API সংস্করণ (শুধুমাত্র gemini-pro)",
SubTitle: "একটি নির্দিষ্ট API সংস্করণ নির্বাচন করুন",
},
GoogleSafetySettings: {
Title: "Google সেফটি ফিল্টার স্তর",
SubTitle: "বিষয়বস্তু ফিল্টার স্তর সেট করুন",
},
},
Baidu: {
ApiKey: {
Title: "API কী",
SubTitle: "স্বনির্ধারিত Baidu API কী ব্যবহার করুন",
Placeholder: "Baidu API কী",
},
SecretKey: {
Title: "সিক্রেট কী",
SubTitle: "স্বনির্ধারিত Baidu সিক্রেট কী ব্যবহার করুন",
Placeholder: "Baidu সিক্রেট কী",
},
Endpoint: {
Title: "ইন্টারফেস ঠিকানা",
SubTitle: "স্বনির্ধারিত সমর্থিত নয়, .env কনফিগারেশনে চলে যান",
},
},
ByteDance: {
ApiKey: {
Title: "ইন্টারফেস কী",
SubTitle: "স্বনির্ধারিত ByteDance API কী ব্যবহার করুন",
Placeholder: "ByteDance API কী",
},
Endpoint: {
Title: "ইন্টারফেস ঠিকানা",
SubTitle: "উদাহরণ:",
},
},
Alibaba: {
ApiKey: {
Title: "ইন্টারফেস কী",
SubTitle: "স্বনির্ধারিত আলিবাবা ক্লাউড API কী ব্যবহার করুন",
Placeholder: "Alibaba Cloud API কী",
},
Endpoint: {
Title: "ইন্টারফেস ঠিকানা",
SubTitle: "উদাহরণ:",
},
},
CustomModel: {
Title: "স্বনির্ধারিত মডেল নাম",
SubTitle:
"স্বনির্ধারিত মডেল বিকল্পগুলি যুক্ত করুন, ইংরেজি কমা দ্বারা আলাদা করুন",
},
},
Model: "মডেল (model)",
Model: "মডেল",
Temperature: {
Title: "যাদুকরিতা (temperature)",
SubTitle: "মান বাড়ালে উত্তর বেশি এলোমেলো হবে",
Title: "তাপমাত্রা",
SubTitle: "আরতি মান বেশি করলে বেশি এলোমেলো আউটপুট হবে",
},
TopP: {
Title: "নিউক্লিয়ার স্যাম্পলিং (top_p)",
SubTitle: "যাদুকরিতা মত, কিন্তু একসাথে পরিবর্তন করবেন না",
Title: "শীর্ষ পি",
SubTitle: "তাপমাত্রা সঙ্গে এই মান পরিবর্তন করবেন না",
},
MaxTokens: {
Title: "একটি উত্তর সীমা (max_tokens)",
SubTitle: "প্রতি ইন্টারঅ্যাকশনে সর্বাধিক টোকেন সংখ্য",
Title: "সর্বাধিক টোকেন",
SubTitle: "ইনপুট টোকেন এবং উৎপাদিত টোকেনের সর্বাধিক দৈর্ঘ্য",
},
PresencePenalty: {
Title: "বিষয়বস্তু তাজা (presence_penalty)",
SubTitle: "মান বাড়ালে নতুন বিষয়ে প্রসারিত হওয়ার সম্ভাবনা বেশি",
Title: "উপস্থিতির জরিমানা",
SubTitle: "আরতি মান বেশি করলে নতুন বিষয়গুলি সম্ভাব্যতা বাড়াতে পারে",
},
FrequencyPenalty: {
Title: "ফ্রিকয়েন্সি পেনাল্টি (frequency_penalty)",
SubTitle: "মান বাড়ালে পুনরাবৃত্তি শব্দ কমানোর সম্ভাবনা বেশি",
Title: "ফ্রিকয়েন্সি জরিমানা",
SubTitle:
"আরতি মান বাড়ালে একই লাইন পুনরায় ব্যাবহার করার সম্ভাবনা হ্রাস পায়",
},
},
Store: {
DefaultTopic: "নতুন চ্যাট",
BotHello: "আপনার জন্য কিছু করতে পারি?",
Error: "একটি ত্রুটি ঘটেছে, পরে আবার চেষ্টা করুন",
DefaultTopic: "নতুন সংলাপ",
BotHello: "হ্যালো! আজকে আপনাকে কিভাবে সাহায্য করতে পারি?",
Error: "কিছু নিয়ে ভুল হয়েছে, পরে আবার চেষ্টা করুন",
Prompt: {
History: (content: string) =>
"এটি পূর্বের চ্যাটের সারাংশ হিসেবে ব্যবহৃত হবে: " + content,
"এটি চ্যাট ইতিহাসের সংক্ষিপ্ত সংকলনের মতো: " + content,
Topic:
"চার থেকে পাঁচটি শব্দ ব্যবহার করে এই বাক্যের সংক্ষিপ্ত থিম দিন, ব্যাখ্যা, বিরাম চিহ্ন, ভাষা, অতিরিক্ত টেক্সট বা বোল্ড না ব্যবহার করুন। যদি কোনো থিম না থাকে তবে সরাসরি 'বেকার' বলুন",
"আমাদের সংলাপটির চার থেকে পাঁচ শব্দের একটি শিরোনাম তৈরি করুন যা আমাদের আলাপের সংক্ষিপ্তসার হিসাবে যোগ হবে না, যেমন অভিবৃত্তি, বিন্যা, উদ্ধৃতি, পূর্বচালক চিহ্ন, পূর্বরোবক্তির যেকোনো চিহ্ন বা অতিরিক্ত পাঠ। মেয়াদশেষ উদ্ধৃতি চেষ্টা করুন",
Summarize:
"আলোচনার বিষয়বস্তু সংক্ষিপ্তভাবে সারাংশ করুন, পরবর্তী কনটেক্সট প্রম্পট হিসবে ব্যবহারের জন্য, ২০০ শব্দের মধ্যে সীমাবদ্ধ রাখুন",
"২০০ শব্দের লম্বা হয়ে মুহূর্তে আলোচনা সংক্ষেপের রপ্তানি করুন, যেটি ভবিষ্যতের প্রম্পট হিসবে ব্যবহার করবেন।",
},
},
Copy: {
Success: "ক্লিপবোর্ডে লেখা হয়েছে",
Failed: "কপি ব্যর্থ হয়েছে, দয়া করে ক্লিপবোর্ড অনুমতি প্রদান করুন",
},
Download: {
Success: "বিষয়বস্তু আপনার ডিরেক্টরিতে ডাউনলোড করা হয়েছে।",
Failed: "ডাউনলোড ব্যর্থ হয়েছে।",
Success: "ক্লিপবোর্ডে কপি করা হয়েছে",
Failed: "কপি ব্যর্থ, অনুমতি প্রদান করার জন্য অনুমতি প্রদান করুন",
},
Context: {
Toast: (x: any) => `${x}টি পূর্বনির্ধারিত প্রম্পট অন্তর্ভুক্ত`,
Toast: (x: any) => `With ${x} contextual prompts`,
Edit: "বর্তমান চ্যাট সেটিংস",
Add: "একটি নতুন চ্যাট যোগ করুন",
Clear: "কনটেক্সট পরি্কার করা হয়েছে",
Revert: "কনটেক্সট পুনরুদ্ধার করুন",
Add: "একটি প্রম্পট যোগ করুন",
Clear: "সঙ্গতি পরি্কার করুন",
Revert: "পূর্ববর্তী অবস্থানে ফিরে যান",
},
Plugin: {
Name: "প্লাগইন",
},
FineTuned: {
Sysmessage: "আপনি একজন সহকারী",
},
SearchChat: {
Name: "অনুসন্ধান",
Page: {
Title: "চ্যাট রেকর্ড অনুসন্ধান করুন",
Search: "অনুসন্ধান কীওয়ার্ড লিখুন",
NoResult: "কোন ফলাফল পাওয়া যায়নি",
NoData: "কোন তথ্য নেই",
Loading: "লোড হচ্ছে",
SubTitle: (count: number) => `${count} টি ফলাফল পাওয়া গেছে`,
},
Item: {
View: "দেখুন",
},
Sysmessage: "আপনি একটি সহকারী যা",
},
Mask: {
Name: "মাস্ক",
Page: {
Title: "পূর্বনির্ধারিত চরিত্র মাস্ক",
SubTitle: (count: number) => `${count}টি পূর্বনির্ধারিত চরিত্র সংজ্ঞা`,
Search: "চরিত্র মাস্ক অনুসন্ধান করুন",
Create: "নতুন তৈরি করুন",
Title: "প্রম্পট টেমপ্লেট",
SubTitle: (count: number) => `${count} টি প্রম্পট টেমপ্লেট`,
Search: "টেমপ্লেট অনুসন্ধান করুন",
Create: "তৈরি করুন",
},
Item: {
Info: (count: number) => `ভিতরে ${count}টি পূর্বনির্ধারিত চ্যাট রয়েছে`,
Info: (count: number) => `${count} প্রম্পট`,
Chat: "চ্যাট",
View: "দেখুন",
Edit: "সম্পাদন করুন",
Edit: "সম্পাদন করুন",
Delete: "মুছে ফেলুন",
DeleteConfirm: "মুছে ফেলার জন্য নিশ্চিত করুন?",
DeleteConfirm: "মুছে ফেলতে নিশ্চিত করুন?",
},
EditModal: {
Title: (readonly: boolean) =>
`ূর্বনির্ধারিত মাস্ক সম্পাদন ${readonly ? "(পঠনযোগ্য)" : ""}`,
Download: "পূর্বনির্ধারিত ডাউনলোড করুন",
Clone: "পূর্বনির্ধারিত ক্লোন করুন",
`্রম্পট টেমপ্লেট সম্পাদন করুন ${readonly ? "(readonly)" : ""}`,
Download: "ডাউনলোড করুন",
Clone: "ক্লোন করুন",
},
Config: {
Avatar: "চরিত্রের চিত্র",
Name: "চরিত্রের নাম",
Avatar: "বট অবতার",
Name: "বটের নাম",
Sync: {
Title: "গ্লোবাল সেটিংস ব্যবহার করুন",
SubTitle: "বর্তমান চ্যাট গ্লোবাল মডেল সেটিংস ব্যবহার করছে কি না",
Title: "গ্লোবাল কনফিগ ব্যবহার করুন",
SubTitle: "এই চ্যাট গ্লোবাল কনফিগ ব্যবহার করুন",
Confirm:
"বর্তমান চ্যাটের কাস্টম সেটিংস স্বয়ংক্রিয়ভাবে ওভাররাইট হবে, গ্লোবাল সেটিংস সক্রিয় করতে নিশ্চিত?",
"গ্লোবাল কনফিগ দ্বারা কাস্টম কনফিগ ওভাররাইড করতে নিশ্চিত করতে?",
},
HideContext: {
Title: "পূর্বনির্ধারিত চ্যাট লুকান",
SubTitle:
"লুকানোর পরে পূর্বনির্ধারিত চ্যাট চ্যাট ইন্টারফেসে প্রদর্শিত হবে না",
Title: "সংশ্লিষ্টতা প্রম্পটগুলি লুকান",
SubTitle: "চ্যাটে সংশ্লিষ্টতা প্রম্পটগুলি দেখাবেন না",
},
Share: {
Title: "এই মাস্ক শেয়ার করুন",
SubTitle: "এই মাস্কের সরাসরি লিঙ্ক তৈরি করুন",
Title: "এই মাস্কটি শেয়ার করুন",
SubTitle: "এই মাস্কের একটি লিঙ্ক তৈরি করুন",
Action: "লিঙ্ক কপি করুন",
},
},
},
NewChat: {
Return: "ফিরে যান",
Skip: "ডাইরেক্ট শুরু করুন",
NotShow: "আবার প্রদর্শন করবেন না",
Skip: "শুরু করুন",
Title: "মাস্ক নির্বাচন করুন",
SubTitle: "মাস্কের পিছনে আত্মার সঙ্গে চ্যাট করুন",
More: "আরো খুঁজুন",
NotShow: "এখনও দেখাবেন না",
ConfirmNoShow:
"নিশ্চিত যে নিষ্ক্রিয় করবেন? নিষ্ক্রিয় করার পরে সেটিংসে পুনরায় সক্রিয় করা যাবে।",
Title: "একটি মাস্ক নির্বাচন করুন",
SubTitle: "এখন শুরু করুন, মাস্কের পিছনের চিন্তা প্রতিক্রিয়া করুন",
More: "সব দেখুন",
},
URLCommand: {
Code: "লিঙ্কে অ্যাক্সেস কোড ইতিমধ্যে অন্তর্ভুক্ত রয়েছে, অটো পূরণ করতে চান?",
Settings:
"লিঙ্কে প্রাক-নির্ধারিত সেটিংস অন্তর্ভুক্ত রয়েছে, অটো পূরণ করতে চান?",
"নিষ্ক্রিয় করতে নিশ্চিত করুন? পরে আপনি এটি সেটিংসে সক্ষম করতে পারবে।",
},
UI: {
Confirm: "নিশ্চিত করুন",
Cancel: "বাতিল করুন",
Close: "বন্ধ করুন",
Create: "নতুন তৈরি করুন",
Edit: "সম্পাদন করুন",
Export: "রপ্তানি করুন",
Import: "আমদানি করুন",
Sync: "সিঙ্ক",
Config: "কনফিগারেশন",
Create: "তৈরি করুন",
Edit: "সম্পাদন করুন",
},
Exporter: {
Description: {
Title: "শুধুমাত্র কনটেক্সট পরিষ্কার করার পরে বার্তাগুলি প্রদর্শিত হবে",
},
Model: "মডেল",
Messages: "বার্তা",
Topic: "থিম",
Topic: "টপিক",
Time: "সময়",
},
};

View File

@@ -1,4 +1,3 @@
import { ShortcutKeyModal } from "../components/chat";
import { getClientConfig } from "../config/client";
import { SubmitKey } from "../store/config";
@@ -43,7 +42,6 @@ const cn = {
PinToastAction: "查看",
Delete: "删除",
Edit: "编辑",
FullScreen: "全屏",
},
Commands: {
new: "新建聊天",
@@ -82,14 +80,6 @@ const cn = {
SaveAs: "存为面具",
},
IsContext: "预设提示词",
ShortcutKey: {
Title: "键盘快捷方式",
newChat: "打开新聊天",
focusInput: "聚焦输入框",
copyLastMessage: "复制最后一个回复",
copyLastCode: "复制最后一个代码块",
showShortcutKey: "显示快捷方式",
},
},
Export: {
Title: "分享聊天记录",
@@ -114,10 +104,6 @@ const cn = {
Toast: "正在生成截图",
Modal: "长按或右键保存图片",
},
Artifacts: {
Title: "分享页面",
Error: "分享失败",
},
},
Select: {
Search: "搜索消息",
@@ -142,7 +128,6 @@ const cn = {
Settings: {
Title: "设置",
SubTitle: "所有设置选项",
ShowPassword: "显示密码",
Danger: {
Reset: {
@@ -167,11 +152,6 @@ const cn = {
Title: "字体大小",
SubTitle: "聊天内容的字体大小",
},
FontFamily: {
Title: "聊天字体",
SubTitle: "聊天内容的字体,若置空则应用全局默认字体",
Placeholder: "字体名称",
},
InjectSystemPrompts: {
Title: "注入系统级提示信息",
SubTitle: "强制给每次请求的消息列表开头添加一个模拟 ChatGPT 的系统提示",
@@ -366,102 +346,6 @@ const cn = {
Title: "API 版本(仅适用于 gemini-pro",
SubTitle: "选择一个特定的 API 版本",
},
GoogleSafetySettings: {
Title: "Google 安全过滤级别",
SubTitle: "设置内容过滤级别",
},
},
Baidu: {
ApiKey: {
Title: "API Key",
SubTitle: "使用自定义 Baidu API Key",
Placeholder: "Baidu API Key",
},
SecretKey: {
Title: "Secret Key",
SubTitle: "使用自定义 Baidu Secret Key",
Placeholder: "Baidu Secret Key",
},
Endpoint: {
Title: "接口地址",
SubTitle: "不支持自定义前往.env配置",
},
},
Tencent: {
ApiKey: {
Title: "API Key",
SubTitle: "使用自定义腾讯云API Key",
Placeholder: "Tencent API Key",
},
SecretKey: {
Title: "Secret Key",
SubTitle: "使用自定义腾讯云Secret Key",
Placeholder: "Tencent Secret Key",
},
Endpoint: {
Title: "接口地址",
SubTitle: "不支持自定义前往.env配置",
},
},
ByteDance: {
ApiKey: {
Title: "接口密钥",
SubTitle: "使用自定义 ByteDance API Key",
Placeholder: "ByteDance API Key",
},
Endpoint: {
Title: "接口地址",
SubTitle: "样例:",
},
},
Alibaba: {
ApiKey: {
Title: "接口密钥",
SubTitle: "使用自定义阿里云API Key",
Placeholder: "Alibaba Cloud API Key",
},
Endpoint: {
Title: "接口地址",
SubTitle: "样例:",
},
},
Moonshot: {
ApiKey: {
Title: "接口密钥",
SubTitle: "使用自定义月之暗面API Key",
Placeholder: "Moonshot API Key",
},
Endpoint: {
Title: "接口地址",
SubTitle: "样例:",
},
},
Stability: {
ApiKey: {
Title: "接口密钥",
SubTitle: "使用自定义 Stability API Key",
Placeholder: "Stability API Key",
},
Endpoint: {
Title: "接口地址",
SubTitle: "样例:",
},
},
Iflytek: {
ApiKey: {
Title: "ApiKey",
SubTitle: "从讯飞星火控制台获取的 APIKey",
Placeholder: "APIKey",
},
ApiSecret: {
Title: "ApiSecret",
SubTitle: "从讯飞星火控制台获取的 APISecret",
Placeholder: "APISecret",
},
Endpoint: {
Title: "接口地址",
SubTitle: "样例:",
},
},
CustomModel: {
Title: "自定义模型名",
@@ -504,8 +388,8 @@ const cn = {
},
},
Copy: {
Success: "已写入剪板",
Failed: "复制失败,请赋予剪板权限",
Success: "已写入剪板",
Failed: "复制失败,请赋予剪板权限",
},
Download: {
Success: "内容已下载到您的目录。",
@@ -518,67 +402,12 @@ const cn = {
Clear: "上下文已清除",
Revert: "恢复上下文",
},
Discovery: {
Name: "发现",
Plugin: {
Name: "插件",
},
FineTuned: {
Sysmessage: "你是一个助手",
},
SearchChat: {
Name: "搜索",
Page: {
Title: "搜索聊天记录",
Search: "输入搜索关键词",
NoResult: "没有找到结果",
NoData: "没有数据",
Loading: "加载中",
SubTitle: (count: number) => `搜索到 ${count} 条结果`,
},
Item: {
View: "查看",
},
},
Plugin: {
Name: "插件",
Page: {
Title: "插件",
SubTitle: (count: number) => `${count} 个插件`,
Search: "搜索插件",
Create: "新建",
Find: "您可以在Github上找到优秀的插件",
},
Item: {
Info: (count: number) => `${count} 方法`,
View: "查看",
Edit: "编辑",
Delete: "删除",
DeleteConfirm: "确认删除?",
},
Auth: {
None: "不需要授权",
Basic: "Basic",
Bearer: "Bearer",
Custom: "自定义",
CustomHeader: "自定义参数名称",
Token: "Token",
Proxy: "使用代理",
ProxyDescription: "使用代理解决 CORS 错误",
Location: "位置",
LocationHeader: "Header",
LocationQuery: "Query",
LocationBody: "Body",
},
EditModal: {
Title: (readonly: boolean) => `编辑插件 ${readonly ? "(只读)" : ""}`,
Download: "下载",
Auth: "授权方式",
Content: "OpenAPI Schema",
Load: "从网页加载",
Method: "方法",
Error: "格式错误",
},
},
Mask: {
Name: "面具",
Page: {
@@ -613,10 +442,6 @@ const cn = {
Title: "隐藏预设对话",
SubTitle: "隐藏后预设对话不会出现在聊天界面",
},
Artifacts: {
Title: "启用Artifacts",
SubTitle: "启用之后可以直接渲染HTML页面",
},
Share: {
Title: "分享此面具",
SubTitle: "生成此面具的直达链接",
@@ -659,61 +484,6 @@ const cn = {
Topic: "主题",
Time: "时间",
},
SdPanel: {
Prompt: "画面提示",
NegativePrompt: "否定提示",
PleaseInput: (name: string) => `请输入${name}`,
AspectRatio: "横纵比",
ImageStyle: "图像风格",
OutFormat: "输出格式",
AIModel: "AI模型",
ModelVersion: "模型版本",
Submit: "提交生成",
ParamIsRequired: (name: string) => `${name}不能为空`,
Styles: {
D3Model: "3D模型",
AnalogFilm: "模拟电影",
Anime: "动漫",
Cinematic: "电影风格",
ComicBook: "漫画书",
DigitalArt: "数字艺术",
Enhance: "增强",
FantasyArt: "幻想艺术",
Isometric: "等角",
LineArt: "线描",
LowPoly: "低多边形",
ModelingCompound: "建模材料",
NeonPunk: "霓虹朋克",
Origami: "折纸",
Photographic: "摄影",
PixelArt: "像素艺术",
TileTexture: "贴图",
},
},
Sd: {
SubTitle: (count: number) => `${count} 条绘画`,
Actions: {
Params: "查看参数",
Copy: "复制提示词",
Delete: "删除",
Retry: "重试",
ReturnHome: "返回首页",
History: "查看历史",
},
EmptyRecord: "暂无绘画记录",
Status: {
Name: "状态",
Success: "成功",
Error: "失败",
Wait: "等待中",
Running: "运行中",
},
Danger: {
Delete: "确认删除?",
},
GenerateParams: "生成参数",
Detail: "详情",
},
};
type DeepPartial<T> = T extends object

View File

@@ -1,562 +1,233 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const cs: PartialLocaleType = {
WIP: "V přípravě...",
Error: {
Unauthorized: isApp
? "Byl zjištěn neplatný API Key, prosím přejděte na stránku [Nastavení](/#/settings) a zkontrolujte, zda je API Key správně nakonfigurován."
: "Heslo je nesprávné nebo prázdné, prosím přejděte na stránku [Přihlášení](/#/auth) a zadejte správné heslo, nebo na stránku [Nastavení](/#/settings) a zadejte svůj vlastní OpenAI API Key.",
},
Auth: {
Title: "Potřebné heslo",
Tips: "Administrátor povolil ověření heslem, prosím zadejte přístupový kód níže",
SubTips: "nebo zadejte svůj OpenAI nebo Google API klíč",
Input: "Zadejte přístupový kód zde",
Confirm: "Potvrdit",
Later: "Později",
Unauthorized:
"Neoprávněný přístup, zadejte přístupový kód na [stránce](/#/auth) nastavení.",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} konverzací`,
ChatItemCount: (count: number) => `${count} zpráv`,
},
Chat: {
SubTitle: (count: number) => `Celkem ${count} konverzací`,
EditMessage: {
Title: "Upravit zprávy",
Topic: {
Title: "Téma konverzace",
SubTitle: "Změnit aktuální téma konverzace",
},
},
SubTitle: (count: number) => `${count} zpráv s ChatGPT`,
Actions: {
ChatList: "Zobrazit seznam zpráv",
CompressedHistory: "Zobrazit komprimovanou historii Prompt",
Export: "Exportovat konverzace",
ChatList: "Přejít na seznam chatů",
CompressedHistory: "Pokyn z komprimované paměti historie",
Export: "Exportovat všechny zprávy jako Markdown",
Copy: "Kopírovat",
Stop: "Zastavit",
Retry: "Zkusit znovu",
Pin: "Připnout",
PinToastContent: "1 konverzace byla připnuta k přednastaveným promptům",
PinToastAction: "Zobrazit",
Retry: "Zopakovat",
Delete: "Smazat",
Edit: "Upravit",
},
Commands: {
new: "Nová konverzace",
newm: "Nová konverzace z masky",
next: "Další konverzace",
prev: "Předchozí konverzace",
clear: "Vymazat kontext",
del: "Smazat konverzaci",
},
InputActions: {
Stop: "Zastavit odpověď",
ToBottom: "Přejít na nejnovější",
Theme: {
auto: "Automatické téma",
light: "Světelný režim",
dark: "Tmavý režim",
},
Prompt: "Rychlé příkazy",
Masks: "Všechny masky",
Clear: "Vymazat konverzaci",
Settings: "Nastavení konverzace",
UploadImage: "Nahrát obrázek",
},
Rename: "Přejmenovat konverzaci",
Typing: "Píše se…",
Rename: "Přejmenovat chat",
Typing: "Píše...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} odeslat`;
var inputHints = `${submitKey} pro odeslání`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter pro nový řádek";
inputHints += ", Shift + Enter pro řádkování";
}
return inputHints + "/ pro doplnění, : pro příkaz";
return inputHints + ", / pro vyhledávání pokynů";
},
Send: "Odeslat",
Config: {
Reset: "Vymazat paměť",
SaveAs: "Uložit jako masku",
Reset: "Obnovit výchozí",
SaveAs: "Uložit jako Masku",
},
IsContext: "Přednastavené prompty",
},
Export: {
Title: "Sdílet konverzace",
Title: "Všechny zprávy",
Copy: "Kopírovat vše",
Download: "Stáhnout soubor",
Share: "Sdílet na ShareGPT",
MessageFromYou: "Uživatel",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Formát exportu",
SubTitle: "Lze exportovat jako Markdown text nebo PNG obrázek",
},
IncludeContext: {
Title: "Zahrnout kontext masky",
SubTitle: "Zobrazit kontext masky ve zprávách",
},
Steps: {
Select: "Vybrat",
Preview: "Náhled",
},
Image: {
Toast: "Generování screenshotu",
Modal: "Dlouhým stiskem nebo pravým tlačítkem myši uložte obrázek",
},
},
Select: {
Search: "Hledat zprávy",
All: "Vybrat vše",
Latest: "Několik posledních",
Clear: "Zrušit výběr",
Download: "Stáhnout",
MessageFromYou: "Zpráva od vás",
MessageFromChatGPT: "Zpráva z ChatGPT",
},
Memory: {
Title: "Historie shrnutí",
EmptyContent: "Obsah konverzace je příliš krátký, není třeba shrnovat",
Send: "Automaticky komprimovat konverzace a odeslat jako kontext",
Copy: "Kopírovat shrnutí",
Reset: "[nepoužívá se]",
ResetConfirm: "Opravdu chcete vymazat historii shrnutí?",
Title: "Pokyn z paměti",
EmptyContent: "Zatím nic.",
Send: "Odeslat paměť",
Copy: "Kopírovat paměť",
Reset: "Obnovit relaci",
ResetConfirm:
"Resetováním se vymaže historie aktuálních konverzací i paměť historie pokynů. Opravdu chcete provést obnovu?",
},
Home: {
NewChat: "Nová konverzace",
DeleteChat: "Opravdu chcete smazat vybranou konverzaci?",
DeleteToast: "Konverzace byla smazána",
Revert: "Vrátit",
NewChat: "Nový chat",
DeleteChat: "Potvrzujete smazání vybrané konverzace?",
DeleteToast: "Chat smazán",
Revert: "Zvrátit",
},
Settings: {
Title: "Nastavení",
SubTitle: "Všechny možnosti nastavení",
SubTitle: "Všechna nastavení",
Danger: {
Reset: {
Title: "Obnovit všechna nastavení",
SubTitle: "Obnovit všechny nastavení na výchozí hodnoty",
Action: "Okamžitě obnovit",
Confirm: "Opravdu chcete obnovit všechna nastavení?",
},
Clear: {
Title: "Smazat všechna data",
SubTitle: "Smazat všechny chaty a nastavení",
Action: "Okamžitě smazat",
Confirm: "Opravdu chcete smazat všechny chaty a nastavení?",
},
},
Lang: {
Name: "Language", // POZOR: pokud chcete přidat nový překlad, prosím, nechte tuto hodnotu jako `Language`
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Všechny jazyky",
},
Avatar: "Profilový obrázek",
Avatar: "Avatar",
FontSize: {
Title: "Velikost písma",
SubTitle: "Velikost písma pro obsah chatu",
},
FontFamily: {
Title: "Chatové Písmo",
SubTitle:
"Písmo obsahu chatu, ponechejte prázdné pro použití globálního výchozího písma",
Placeholder: "Název Písma",
SubTitle: "Nastavení velikosti písma obsahu chatu",
},
InjectSystemPrompts: {
Title: "Vložit systémové výzvy",
Title: "Vložit systémové prompty",
SubTitle:
"Automaticky přidat systémovou výzvu simulující ChatGPT na začátek seznamu zpráv pro každý požadavek",
"Vynutit přidání simulovaného systémového promptu ChatGPT na začátek seznamu zpráv každého požadavku",
},
InputTemplate: {
Title: "Předzpracování uživatelského vstupu",
SubTitle: "Nejnovější zpráva uživatele bude vyplněna do této šablony",
},
Update: {
Version: (x: string) => `Aktuální verze: ${x}`,
IsLatest: "Jste na nejnovější verzi",
Version: (x: string) => `Verze: ${x}`,
IsLatest: "Aktuální verze",
CheckUpdate: "Zkontrolovat aktualizace",
IsChecking: "Kontrola aktualizací...",
IsChecking: "Kontrola aktualizace...",
FoundUpdate: (x: string) => `Nalezena nová verze: ${x}`,
GoToUpdate: "Přejít na aktualizaci",
GoToUpdate: "Aktualizovat",
},
SendKey: "Klávesa pro odeslání",
SendKey: "Odeslat klíč",
Theme: "Téma",
TightBorder: "Režim bez okra",
TightBorder: "Těsné ohraničení",
SendPreviewBubble: {
Title: "Náhledová bublina",
SubTitle: "Náhled Markdown obsahu v náhledové bublině",
},
AutoGenerateTitle: {
Title: "Automatické generování názvu",
SubTitle: "Generovat vhodný název na základě obsahu konverzace",
},
Sync: {
CloudState: "Data na cloudu",
NotSyncYet: "Ještě nebylo synchronizováno",
Success: "Synchronizace úspěšná",
Fail: "Synchronizace selhala",
Config: {
Modal: {
Title: "Nastavení cloudové synchronizace",
Check: "Zkontrolovat dostupnost",
},
SyncType: {
Title: "Typ synchronizace",
SubTitle: "Vyberte oblíbený synchronizační server",
},
Proxy: {
Title: "Povolit proxy",
SubTitle:
"Při synchronizaci v prohlížeči musí být proxy povolena, aby se předešlo problémům s CORS",
},
ProxyUrl: {
Title: "Adresa proxy",
SubTitle: "Pouze pro interní proxy",
},
WebDav: {
Endpoint: "WebDAV adresa",
UserName: "Uživatelské jméno",
Password: "Heslo",
},
UpStash: {
Endpoint: "UpStash Redis REST URL",
UserName: "Název zálohy",
Password: "UpStash Redis REST Token",
},
},
LocalState: "Lokální data",
Overview: (overview: any) => {
return `${overview.chat} konverzací, ${overview.message} zpráv, ${overview.prompt} promptů, ${overview.mask} masek`;
},
ImportFailed: "Import selhal",
Title: "Odesílat chatovací bublinu s náhledem",
SubTitle: "Zobrazit v náhledu bubliny",
},
Mask: {
Splash: {
Title: "Úvodní stránka masky",
SubTitle: "Při zahájení nové konverzace zobrazit úvodní stránku masky",
},
Builtin: {
Title: "Skrýt vestavěné masky",
SubTitle: "Skrýt vestavěné masky v seznamu všech masek",
Title: "Úvodní obrazovka Masek",
SubTitle: "Před zahájením nového chatu zobrazte úvodní obrazovku Masek",
},
},
Prompt: {
Disable: {
Title: "Zakázat automatické doplňování promptů",
SubTitle:
"Automatické doplňování se aktivuje zadáním / na začátku textového pole",
Title: "Deaktivovat automatické dokončování",
SubTitle: "Zadejte / pro spuštění automatického dokončování",
},
List: "Seznam vlastních promptů",
List: "Seznam pokynů",
ListCount: (builtin: number, custom: number) =>
`Vestavěné ${builtin} položek, uživatelsky definované ${custom} položek`,
`${builtin} vestavěných, ${custom} uživatelských`,
Edit: "Upravit",
Modal: {
Title: "Seznam promptů",
Add: "Nový",
Search: "Hledat prompty",
Title: "Seznam pokynů",
Add: "Přidat pokyn",
Search: "Hledat pokyny",
},
EditModal: {
Title: "Upravit prompt",
Title: "Editovat pokyn",
},
},
HistoryCount: {
Title: "Počet historických zpráv",
SubTitle: "Počet historických zpráv zahrnutých v každém požadavku",
Title: "Počet připojených zpráv",
SubTitle: "Počet odeslaných připojených zpráv na žádost",
},
CompressThreshold: {
Title: "Prahová hodnota komprese historických zpráv",
Title: "Práh pro kompresi historie",
SubTitle:
"Když nekomprimované historické zprávy překročí tuto hodnotu, dojde ke kompresi",
"Komprese proběhne, pokud délka nekomprimovaných zpráv přesáhne tuto hodnotu",
},
Usage: {
Title: "Kontrola zůstatku",
Title: "Stav účtu",
SubTitle(used: any, total: any) {
return `Tento měsíc použito $${used}, celkový předplatný objem $${total}`;
return `Použito tento měsíc $${used}, předplaceno $${total}`;
},
IsChecking: "Probíhá kontrola…",
Check: "Znovu zkontrolovat",
NoAccess: "Zadejte API Key nebo přístupové heslo pro zobrazení zůstatku",
IsChecking: "Kontroluji...",
Check: "Zkontrolovat",
NoAccess: "Pro kontrolu zůstatku zadejte klíč API",
},
Access: {
AccessCode: {
Title: "Přístupový kód",
SubTitle: "Administrátor aktivoval šifrovaný přístup",
Placeholder: "Zadejte přístupový kód",
},
CustomEndpoint: {
Title: "Vlastní rozhraní",
SubTitle: "Použít vlastní Azure nebo OpenAI službu",
},
Provider: {
Title: "Poskytovatel modelu",
SubTitle: "Přepnout mezi různými poskytovateli",
},
OpenAI: {
ApiKey: {
Title: "API Key",
SubTitle:
"Použijte vlastní OpenAI Key k obejití přístupového omezení",
Placeholder: "OpenAI API Key",
},
Endpoint: {
Title: "Adresa rozhraní",
SubTitle: "Kromě výchozí adresy musí obsahovat http(s)://",
},
},
Azure: {
ApiKey: {
Title: "Rozhraní klíč",
SubTitle: "Použijte vlastní Azure Key k obejití přístupového omezení",
Placeholder: "Azure API Key",
},
Endpoint: {
Title: "Adresa rozhraní",
SubTitle: "Příklad:",
},
ApiVerion: {
Title: "Verze rozhraní (azure api version)",
SubTitle: "Vyberte konkrétní verzi",
},
},
Anthropic: {
ApiKey: {
Title: "Rozhraní klíč",
SubTitle:
"Použijte vlastní Anthropic Key k obejití přístupového omezení",
Placeholder: "Anthropic API Key",
},
Endpoint: {
Title: "Adresa rozhraní",
SubTitle: "Příklad:",
},
ApiVerion: {
Title: "Verze rozhraní (claude api version)",
SubTitle: "Vyberte konkrétní verzi API",
},
},
Google: {
ApiKey: {
Title: "API klíč",
SubTitle: "Získejte svůj API klíč od Google AI",
Placeholder: "Zadejte svůj Google AI Studio API klíč",
},
Endpoint: {
Title: "Konečná adresa",
SubTitle: "Příklad:",
},
ApiVersion: {
Title: "Verze API (pouze pro gemini-pro)",
SubTitle: "Vyberte konkrétní verzi API",
},
GoogleSafetySettings: {
Title: "Úroveň bezpečnostního filtrování Google",
SubTitle: "Nastavit úroveň filtrování obsahu",
},
},
Baidu: {
ApiKey: {
Title: "API Key",
SubTitle: "Použijte vlastní Baidu API Key",
Placeholder: "Baidu API Key",
},
SecretKey: {
Title: "Secret Key",
SubTitle: "Použijte vlastní Baidu Secret Key",
Placeholder: "Baidu Secret Key",
},
Endpoint: {
Title: "Adresa rozhraní",
SubTitle:
"Nepodporuje vlastní nastavení, přejděte na .env konfiguraci",
},
},
ByteDance: {
ApiKey: {
Title: "Rozhraní klíč",
SubTitle: "Použijte vlastní ByteDance API Key",
Placeholder: "ByteDance API Key",
},
Endpoint: {
Title: "Adresa rozhraní",
SubTitle: "Příklad:",
},
},
Alibaba: {
ApiKey: {
Title: "Rozhraní klíč",
SubTitle: "Použijte vlastní Alibaba Cloud API Key",
Placeholder: "Alibaba Cloud API Key",
},
Endpoint: {
Title: "Adresa rozhraní",
SubTitle: "Příklad:",
},
},
CustomModel: {
Title: "Vlastní názvy modelů",
SubTitle: "Přidejte možnosti vlastních modelů, oddělené čárkami",
},
},
Model: "Model (model)",
Model: "Model",
Temperature: {
Title: "Náhodnost (temperature)",
SubTitle: "Čím vyšší hodnota, tím náhodnější odpovědi",
},
TopP: {
Title: "Jádrové vzorkování (top_p)",
SubTitle: "Podobné náhodnosti, ale neměňte spolu s náhodností",
Title: "Teplota",
SubTitle: "Větší hodnota činí výstup náhodnějším",
},
MaxTokens: {
Title: "Omezení odpovědi (max_tokens)",
SubTitle: "Maximální počet Tokenů použitých v jednom interakci",
Title: "Max. počet tokenů",
SubTitle: "Maximální délka vstupního tokenu a generovaných tokenů",
},
PresencePenalty: {
Title: "Čerstvost témat (presence_penalty)",
SubTitle:
"Čím vyšší hodnota, tím větší pravděpodobnost rozšíření na nová témata",
Title: "Přítomnostní korekce",
SubTitle: "Větší hodnota zvyšuje pravděpodobnost nových témat.",
},
FrequencyPenalty: {
Title: "Penalizace frekvence (frequency_penalty)",
Title: "Frekvenční penalizace",
SubTitle:
"Čím vyšší hodnota, tím větší pravděpodobnost snížení opakování slov",
"Větší hodnota snižující pravděpodobnost opakování stejného řádku",
},
},
Store: {
DefaultTopic: "Nový chat",
BotHello: "Jak vám mohu pomoci?",
Error: "Došlo k chybě, zkuste to prosím znovu později.",
DefaultTopic: "Nová konverzace",
BotHello: "Ahoj! Jak mohu dnes pomoci?",
Error: "Něco se pokazilo, zkuste to prosím později.",
Prompt: {
History: (content: string) =>
"Toto je shrnutí historie chatu jako kontext: " + content,
"Toto je shrnutí historie chatu mezi umělou inteligencí a uživatelem v podobě rekapitulace: " +
content,
Topic:
"Použijte čtyři až pět slov pro stručné téma této věty, bez vysvětlení, interpunkce, citoslovcí, nadbytečného textu, bez tučného písma. Pokud téma neexistuje, vraťte pouze 'neformální chat'.",
"Vytvořte prosím název o čtyřech až pěti slovech vystihující průběh našeho rozhovoru bez jakýchkoli úvodních slov, interpunkčních znamének, uvozovek, teček, symbolů nebo dalšího textu. Odstraňte uvozovky.",
Summarize:
"Stručně shrňte obsah konverzace jako kontextový prompt pro budoucí použití, do 200 slov",
"Krátce shrň naši diskusi v rozsahu do 200 slov a použij ji jako podnět pro budoucí kontext.",
},
},
Copy: {
Success: "Zkopírováno do schránky",
Failed: "Kopírování selhalo, prosím, povolte přístup ke schránce",
},
Download: {
Success: "Obsah byl stažen do vašeho adresáře.",
Failed: "Stahování selhalo.",
},
Context: {
Toast: (x: any) => `Obsahuje ${x} přednastavených promptů`,
Edit: "Nastavení aktuální konverzace",
Add: "Přidat novou konverzaci",
Clear: "Kontext byl vymazán",
Revert: "Obnovit kontext",
Toast: (x: any) => `Použití ${x} kontextových pokynů`,
Edit: "Kontextové a paměťové pokyny",
Add: "Přidat pokyn",
},
Plugin: {
Name: "Plugin",
},
FineTuned: {
Sysmessage: "Jste asistent",
},
SearchChat: {
Name: "Hledat",
Page: {
Title: "Hledat v historii chatu",
Search: "Zadejte hledané klíčové slovo",
NoResult: "Nebyly nalezeny žádné výsledky",
NoData: "Žádná data",
Loading: "Načítání",
SubTitle: (count: number) => `Nalezeno ${count} výsledků`,
},
Item: {
View: "Zobrazit",
},
Sysmessage: "Jste asistent, který",
},
Mask: {
Name: "Maska",
Page: {
Title: "Přednastavené role masky",
SubTitle: (count: number) => `${count} definovaných rolí`,
Search: "Hledat role masky",
Create: "Nový",
Title: "Šablona pokynu",
SubTitle: (count: number) => `${count} šablon pokynů`,
Search: "Hledat v šablonách",
Create: "Vytvořit",
},
Item: {
Info: (count: number) => `Obsahuje ${count} přednastavených konverzací`,
Info: (count: number) => `${count} pokynů`,
Chat: "Chat",
View: "Zobrazit",
Edit: "Upravit",
Delete: "Smazat",
DeleteConfirm: "Opravdu chcete smazat?",
DeleteConfirm: "Potvrdit smazání?",
},
EditModal: {
Title: (readonly: boolean) =>
`Upravit přednastavenou masku ${readonly ? " (jen pro čtení)" : ""}`,
Download: "Stáhnout přednastavení",
Clone: "Klonovat přednastavení",
`Editovat šablonu pokynu ${readonly ? "(pouze ke čtení)" : ""}`,
Download: "Stáhnout",
Clone: "Duplikovat",
},
Config: {
Avatar: "Profilový obrázek",
Name: "Název role",
Sync: {
Title: "Použít globální nastavení",
SubTitle: "Použít globální modelová nastavení pro aktuální konverzaci",
Confirm:
"Vaše vlastní nastavení konverzace bude automaticky přepsáno, opravdu chcete použít globální nastavení?",
},
HideContext: {
Title: "Skrýt přednastavené konverzace",
SubTitle:
"Po skrytí se přednastavené konverzace nebudou zobrazovat v chatovém rozhraní",
},
Share: {
Title: "Sdílet tuto masku",
SubTitle: "Generovat přímý odkaz na tuto masku",
Action: "Kopírovat odkaz",
},
Avatar: "Avatar Bota",
Name: "Jméno Bota",
},
},
NewChat: {
Return: "Zpět",
Skip: "Začít hned",
NotShow: "Zobrazit už nikdy",
ConfirmNoShow:
"Opravdu chcete zakázat? Zakázání můžete kdykoli znovu povolit v nastavení.",
Title: "Vyberte masku",
SubTitle: "Začněte nyní a konfrontujte se s myslí za maskou",
More: "Zobrazit vše",
},
URLCommand: {
Code: "Byl detekován přístupový kód v odkazu, chcete jej automaticky vyplnit?",
Settings:
"Byla detekována přednastavená nastavení v odkazu, chcete je automaticky vyplnit?",
Skip: "Přeskočit",
Title: "Vyberte Masku",
SubTitle: "Chatovat s duší za Maskou",
More: "Najít více",
NotShow: "Nezobrazovat znovu",
ConfirmNoShow: "Potvrdit zakázáníMůžete jej povolit později v nastavení.",
},
UI: {
Confirm: "Potvrdit",
Cancel: "Zrušit",
Close: "Zavřít",
Create: "Nový",
Create: "Vytvořit",
Edit: "Upravit",
Export: "Exportovat",
Import: "Importovat",
Sync: "Synchronizovat",
Config: "Konfigurovat",
},
Exporter: {
Description: {
Title: "Pouze zprávy po vymazání kontextu budou zobrazeny",
},
Model: "Model",
Messages: "Zprávy",
Topic: "Téma",

View File

@@ -1,580 +1,235 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const de: PartialLocaleType = {
WIP: "In Bearbeitung...",
Error: {
Unauthorized: isApp
? "Ungültiger API-Schlüssel erkannt. Bitte gehen Sie zur [Einstellungen](/#/settings) Seite, um zu überprüfen, ob der API-Schlüssel korrekt konfiguriert ist."
: "Das Passwort ist falsch oder leer. Bitte gehen Sie zur [Login](/#/auth) Seite, um das richtige Passwort einzugeben, oder fügen Sie Ihren OpenAI API-Schlüssel auf der [Einstellungen](/#/settings) Seite hinzu.",
},
Auth: {
Title: "Passwort erforderlich",
Tips: "Der Administrator hat die Passwortüberprüfung aktiviert. Bitte geben Sie den Zugangscode unten ein.",
SubTips: "Oder geben Sie Ihren OpenAI oder Google API-Schlüssel ein.",
Input: "Geben Sie hier den Zugangscode ein",
Confirm: "Bestätigen",
Later: "Später",
Unauthorized:
"Unbefugter Zugriff, bitte geben Sie den Zugangscode auf der [Einstellungsseite](/#/auth) ein.",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} Gespräche`,
ChatItemCount: (count: number) => `${count} Nachrichten`,
},
Chat: {
SubTitle: (count: number) => `Insgesamt ${count} Gespräche`,
EditMessage: {
Title: "Nachricht bearbeiten",
Topic: {
Title: "Chat-Thema",
SubTitle: "Ändern Sie das aktuelle Chat-Thema",
},
},
SubTitle: (count: number) => `${count} Nachrichten mit ChatGPT`,
Actions: {
ChatList: "Nachrichtliste anzeigen",
CompressedHistory: "Komprimierte Historie anzeigen",
Export: "Chatverlauf exportieren",
ChatList: "Zur Chat-Liste gehen",
CompressedHistory: "Komprimierter Gedächtnis-Prompt",
Export: "Alle Nachrichten als Markdown exportieren",
Copy: "Kopieren",
Stop: "Stoppen",
Retry: "Erneut versuchen",
Pin: "Anheften",
PinToastContent: "1 Gespräch an den voreingestellten Prompt angeheftet",
PinToastAction: "Ansehen",
Delete: "Löschen",
Edit: "Bearbeiten",
Stop: "Stop",
Retry: "Wiederholen",
Delete: "Delete",
},
Commands: {
new: "Neues Gespräch",
newm: "Neues Gespräch aus Maske erstellen",
next: "Nächstes Gespräch",
prev: "Vorheriges Gespräch",
clear: "Kontext löschen",
del: "Gespräch löschen",
},
InputActions: {
Stop: "Antwort stoppen",
ToBottom: "Zum neuesten Beitrag",
Theme: {
auto: "Automatisches Thema",
light: "Helles Thema",
dark: "Dunkles Thema",
},
Prompt: "Schnellbefehle",
Masks: "Alle Masken",
Clear: "Chat löschen",
Settings: "Gesprächseinstellungen",
UploadImage: "Bild hochladen",
},
Rename: "Gespräch umbenennen",
Typing: "Tippt…",
Rename: "Chat umbenennen",
Typing: "Tippen...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} senden`;
var inputHints = `${submitKey} um zu Senden`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter für Zeilenumbruch";
inputHints += ", Umschalt + Eingabe für Zeilenumbruch";
}
return inputHints + "/ für Autovervollständigung, : für Befehle";
return inputHints + ", / zum Durchsuchen von Prompts";
},
Send: "Senden",
Config: {
Reset: "Erinnerung löschen",
SaveAs: "Als Maske speichern",
Reset: "Reset to Default",
SaveAs: "Save as Mask",
},
IsContext: "Voreingestellter Prompt",
},
Export: {
Title: "Chatverlauf teilen",
Title: "Alle Nachrichten",
Copy: "Alles kopieren",
Download: "Datei herunterladen",
Share: "Auf ShareGPT teilen",
MessageFromYou: "Benutzer",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Exportformat",
SubTitle: "Kann als Markdown-Text oder PNG-Bild exportiert werden",
},
IncludeContext: {
Title: "Maske Kontext einbeziehen",
SubTitle: "Soll der Maskenkontext in den Nachrichten angezeigt werden?",
},
Steps: {
Select: "Auswählen",
Preview: "Vorschau",
},
Image: {
Toast: "Screenshot wird erstellt",
Modal: "Lang drücken oder Rechtsklick, um Bild zu speichern",
},
},
Select: {
Search: "Nachrichten suchen",
All: "Alles auswählen",
Latest: "Neueste",
Clear: "Auswahl aufheben",
Download: "Herunterladen",
MessageFromYou: "Deine Nachricht",
MessageFromChatGPT: "Nachricht von ChatGPT",
},
Memory: {
Title: "Historische Zusammenfassung",
EmptyContent:
"Gesprächsinhalte sind zu kurz, keine Zusammenfassung erforderlich",
Send: "Chatverlauf automatisch komprimieren und als Kontext senden",
Copy: "Zusammenfassung kopieren",
Reset: "[nicht verwendet]",
ResetConfirm: "Zusammenfassung löschen bestätigen?",
Title: "Gedächtnis-Prompt",
EmptyContent: "Noch nichts.",
Send: "Gedächtnis senden",
Copy: "Gedächtnis kopieren",
Reset: "Sitzung zurücksetzen",
ResetConfirm:
"Das Zurücksetzen löscht den aktuellen Gesprächsverlauf und das Langzeit-Gedächtnis. Möchten Sie wirklich zurücksetzen?",
},
Home: {
NewChat: "Neues Gespräch",
DeleteChat: "Bestätigen Sie das Löschen des ausgewählten Gesprächs?",
DeleteToast: "Gespräch gelöscht",
Revert: "Rückgängig machen",
NewChat: "Neuer Chat",
DeleteChat: "Bestätigen Sie, um das ausgewählte Gespräch zu löschen?",
DeleteToast: "Chat gelöscht",
Revert: "Zurücksetzen",
},
Settings: {
Title: "Einstellungen",
SubTitle: "Alle Einstellungsmöglichkeiten",
SubTitle: "Alle Einstellungen",
Danger: {
Reset: {
Title: "Alle Einstellungen zurücksetzen",
SubTitle: "Setzt alle Einstellungen auf die Standardwerte zurück",
Action: "Jetzt zurücksetzen",
Confirm: "Bestätigen Sie das Zurücksetzen aller Einstellungen?",
},
Clear: {
Title: "Alle Daten löschen",
SubTitle: "Löscht alle Chats und Einstellungsdaten",
Action: "Jetzt löschen",
Confirm:
"Bestätigen Sie das Löschen aller Chats und Einstellungsdaten?",
},
},
Lang: {
Name: "Sprache", // ACHTUNG: Wenn Sie eine neue Übersetzung hinzufügen möchten, übersetzen Sie diesen Wert bitte nicht, lassen Sie ihn als `Sprache`
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Alle Sprachen",
},
Avatar: "Avatar",
FontSize: {
Title: "Schriftgröße",
SubTitle: "Schriftgröße des Chat-Inhalts",
},
FontFamily: {
Title: "Chat-Schriftart",
SubTitle:
"Schriftart des Chat-Inhalts, leer lassen, um die globale Standardschriftart anzuwenden",
Placeholder: "Schriftartname",
SubTitle: "Schriftgröße des Chat-Inhalts anpassen",
},
InjectSystemPrompts: {
Title: "Systemweite Eingabeaufforderungen einfügen",
Title: "System-Prompts einfügen",
SubTitle:
"Fügt jeder Nachricht am Anfang der Nachrichtenliste eine simulierte ChatGPT-Systemaufforderung hinzu",
"Erzwingt das Hinzufügen eines simulierten systemweiten Prompts von ChatGPT am Anfang der Nachrichtenliste bei jeder Anfrage",
},
InputTemplate: {
Title: "Benutzer-Eingabeverarbeitung",
SubTitle:
"Die neueste Nachricht des Benutzers wird in diese Vorlage eingefügt",
},
Update: {
Version: (x: string) => `Aktuelle Version: ${x}`,
IsLatest: "Bereits die neueste Version",
CheckUpdate: "Auf Updates überprüfen",
IsChecking: "Überprüfe auf Updates...",
Version: (x: string) => `Version: ${x}`,
IsLatest: "Neueste Version",
CheckUpdate: "Update prüfen",
IsChecking: "Update wird geprüft...",
FoundUpdate: (x: string) => `Neue Version gefunden: ${x}`,
GoToUpdate: "Zum Update gehen",
GoToUpdate: "Aktualisieren",
},
SendKey: "Sende-Taste",
Theme: "Thema",
TightBorder: "Randloser Modus",
SendKey: "Senden-Taste",
Theme: "Erscheinungsbild",
TightBorder: "Enger Rahmen",
SendPreviewBubble: {
Title: "Vorschau-Bubble",
SubTitle: "Markdown-Inhalt in der Vorschau-Bubble anzeigen",
},
AutoGenerateTitle: {
Title: "Titel automatisch generieren",
SubTitle:
"Basierend auf dem Chat-Inhalt einen passenden Titel generieren",
},
Sync: {
CloudState: "Cloud-Daten",
NotSyncYet: "Noch nicht synchronisiert",
Success: "Synchronisation erfolgreich",
Fail: "Synchronisation fehlgeschlagen",
Config: {
Modal: {
Title: "Cloud-Synchronisation konfigurieren",
Check: "Verfügbarkeit überprüfen",
},
SyncType: {
Title: "Synchronisationstyp",
SubTitle: "Wählen Sie den bevorzugten Synchronisationsserver aus",
},
Proxy: {
Title: "Proxy aktivieren",
SubTitle:
"Beim Synchronisieren im Browser muss ein Proxy aktiviert werden, um Cross-Origin-Beschränkungen zu vermeiden",
},
ProxyUrl: {
Title: "Proxy-Adresse",
SubTitle: "Nur für projektinterne Cross-Origin-Proxy",
},
WebDav: {
Endpoint: "WebDAV-Adresse",
UserName: "Benutzername",
Password: "Passwort",
},
UpStash: {
Endpoint: "UpStash Redis REST-Url",
UserName: "Sicherungsname",
Password: "UpStash Redis REST-Token",
},
},
LocalState: "Lokale Daten",
Overview: (overview: any) => {
return `${overview.chat} Chats, ${overview.message} Nachrichten, ${overview.prompt} Eingabeaufforderungen, ${overview.mask} Masken`;
},
ImportFailed: "Import fehlgeschlagen",
Title: "Vorschau-Bubble senden",
SubTitle: "Preview markdown in bubble",
},
Mask: {
Splash: {
Title: "Masken-Startseite",
SubTitle:
"Zeige die Masken-Startseite beim Erstellen eines neuen Chats",
},
Builtin: {
Title: "Eingebaute Masken ausblenden",
SubTitle: "Blendet eingebaute Masken in allen Maskenlisten aus",
Title: "Mask Splash Screen",
SubTitle: "Show a mask splash screen before starting new chat",
},
},
Prompt: {
Disable: {
Title: "Automatische Eingabeaufforderung deaktivieren",
SubTitle:
"Geben Sie am Anfang des Eingabefelds / ein, um die automatische Vervollständigung auszulösen",
Title: "Autovervollständigung deaktivieren",
SubTitle: "Autovervollständigung mit / starten",
},
List: "Benutzerdefinierte Eingabeaufforderungsliste",
List: "Prompt-Liste",
ListCount: (builtin: number, custom: number) =>
`Eingebaut ${builtin} Stück, Benutzerdefiniert ${custom} Stück`,
`${builtin} integriert, ${custom} benutzerdefiniert`,
Edit: "Bearbeiten",
Modal: {
Title: "Eingabeaufforderungsliste",
Add: "Neu erstellen",
Search: "Eingabeaufforderungen suchen",
Title: "Prompt List",
Add: "Add One",
Search: "Search Prompts",
},
EditModal: {
Title: "Eingabeaufforderung bearbeiten",
Title: "Edit Prompt",
},
},
HistoryCount: {
Title: "Anzahl der historischen Nachrichten",
SubTitle:
"Anzahl der historischen Nachrichten, die bei jeder Anfrage mitgesendet werden",
Title: "Anzahl der angehängten Nachrichten",
SubTitle: "Anzahl der pro Anfrage angehängten gesendeten Nachrichten",
},
CompressThreshold: {
Title: "Komprimierungsschwelle für historische Nachrichtenlänge",
Title: "Schwellenwert für Verlaufskomprimierung",
SubTitle:
"Wenn die unkomprimierten historischen Nachrichten diesen Wert überschreiten, wird komprimiert",
"Komprimierung, wenn die Länge der unkomprimierten Nachrichten den Wert überschreitet",
},
Usage: {
Title: "Guthabenabfrage",
Title: "Kontostand",
SubTitle(used: any, total: any) {
return `In diesem Monat verwendet $${used}, Abonnement insgesamt $${total}`;
return `Diesen Monat ausgegeben $${used}, Abonnement $${total}`;
},
IsChecking: "Wird überprüft",
Check: "Erneut überprüfen",
NoAccess:
"Geben Sie API-Schlüssel oder Zugangspasswort ein, um das Guthaben einzusehen",
IsChecking: "Wird überprüft...",
Check: "Erneut prüfen",
NoAccess: "API-Schlüssel eingeben, um den Kontostand zu überprüfen",
},
Access: {
AccessCode: {
Title: "Zugangscode",
SubTitle:
"Der Administrator hat die verschlüsselte Zugriffskontrolle aktiviert",
Placeholder: "Geben Sie den Zugangscode ein",
},
CustomEndpoint: {
Title: "Benutzerdefinierte Schnittstelle",
SubTitle: "Benutzerdefinierte Azure- oder OpenAI-Dienste verwenden",
},
Provider: {
Title: "Modellanbieter",
SubTitle: "Wechseln Sie zu verschiedenen Anbietern",
},
OpenAI: {
ApiKey: {
Title: "API-Schlüssel",
SubTitle:
"Verwenden Sie benutzerdefinierten OpenAI-Schlüssel, um Passwortzugangsbeschränkungen zu umgehen",
Placeholder: "OpenAI API-Schlüssel",
},
Endpoint: {
Title: "Schnittstellenadresse",
SubTitle: "Neben der Standardadresse muss http(s):// enthalten sein",
},
},
Azure: {
ApiKey: {
Title: "Schnittstellenschlüssel",
SubTitle:
"Verwenden Sie benutzerdefinierten Azure-Schlüssel, um Passwortzugangsbeschränkungen zu umgehen",
Placeholder: "Azure API-Schlüssel",
},
Endpoint: {
Title: "Schnittstellenadresse",
SubTitle: "Beispiel:",
},
ApiVerion: {
Title: "Schnittstellenversion (azure api version)",
SubTitle: "Wählen Sie eine spezifische Teilversion aus",
},
},
Anthropic: {
ApiKey: {
Title: "Schnittstellenschlüssel",
SubTitle:
"Verwenden Sie benutzerdefinierten Anthropic-Schlüssel, um Passwortzugangsbeschränkungen zu umgehen",
Placeholder: "Anthropic API-Schlüssel",
},
Endpoint: {
Title: "Schnittstellenadresse",
SubTitle: "Beispiel:",
},
ApiVerion: {
Title: "Schnittstellenversion (claude api version)",
SubTitle: "Wählen Sie eine spezifische API-Version aus",
},
},
Google: {
ApiKey: {
Title: "API-Schlüssel",
SubTitle: "Holen Sie sich Ihren API-Schlüssel von Google AI",
Placeholder: "Geben Sie Ihren Google AI Studio API-Schlüssel ein",
},
Endpoint: {
Title: "Endpunktadresse",
SubTitle: "Beispiel:",
},
ApiVersion: {
Title: "API-Version (nur für gemini-pro)",
SubTitle: "Wählen Sie eine spezifische API-Version aus",
},
GoogleSafetySettings: {
Title: "Google Sicherheitsfilterstufe",
SubTitle: "Inhaltfilterstufe einstellen",
},
},
Baidu: {
ApiKey: {
Title: "API-Schlüssel",
SubTitle: "Verwenden Sie benutzerdefinierten Baidu API-Schlüssel",
Placeholder: "Baidu API-Schlüssel",
},
SecretKey: {
Title: "Geheimschlüssel",
SubTitle: "Verwenden Sie benutzerdefinierten Baidu Geheimschlüssel",
Placeholder: "Baidu Geheimschlüssel",
},
Endpoint: {
Title: "Schnittstellenadresse",
SubTitle:
"Keine benutzerdefinierten Adressen unterstützen, konfigurieren Sie in .env",
},
},
ByteDance: {
ApiKey: {
Title: "Schnittstellenschlüssel",
SubTitle: "Verwenden Sie benutzerdefinierten ByteDance API-Schlüssel",
Placeholder: "ByteDance API-Schlüssel",
},
Endpoint: {
Title: "Schnittstellenadresse",
SubTitle: "Beispiel:",
},
},
Alibaba: {
ApiKey: {
Title: "Schnittstellenschlüssel",
SubTitle:
"Verwenden Sie benutzerdefinierten Alibaba Cloud API-Schlüssel",
Placeholder: "Alibaba Cloud API-Schlüssel",
},
Endpoint: {
Title: "Schnittstellenadresse",
SubTitle: "Beispiel:",
},
},
CustomModel: {
Title: "Benutzerdefinierter Modellname",
SubTitle:
"Fügen Sie benutzerdefinierte Modelloptionen hinzu, getrennt durch Kommas",
},
},
Model: "Modell",
Temperature: {
Title: "Zufälligkeit (temperature)",
SubTitle: "Je höher der Wert, desto zufälliger die Antwort",
},
TopP: {
Title: "Kern-Sampling (top_p)",
SubTitle:
"Ähnlich der Zufälligkeit, aber nicht zusammen mit Zufälligkeit ändern",
Title: "Temperature", //Temperatur
SubTitle: "Ein größerer Wert führt zu zufälligeren Antworten",
},
MaxTokens: {
Title: "Maximale Token-Anzahl pro Antwort",
SubTitle: "Maximale Anzahl der Tokens pro Interaktion",
Title: "Max Tokens", //Maximale Token
SubTitle: "Maximale Anzahl der Anfrage- plus Antwort-Token",
},
PresencePenalty: {
Title: "Themenfrische (presence_penalty)",
Title: "Presence Penalty", //Anwesenheitsstrafe
SubTitle:
"Je höher der Wert, desto wahrscheinlicher wird auf neue Themen eingegangen",
"Ein größerer Wert erhöht die Wahrscheinlichkeit, dass über neue Themen gesprochen wird",
},
FrequencyPenalty: {
Title: "Häufigkeitsstrafe (frequency_penalty)",
Title: "Frequency Penalty", // HäufigkeitStrafe
SubTitle:
"Je höher der Wert, desto wahrscheinlicher werden wiederholte Wörter reduziert",
"Ein größerer Wert, der die Wahrscheinlichkeit verringert, dass dieselbe Zeile wiederholt wird",
},
},
Store: {
DefaultTopic: "Neuer Chat",
BotHello: "Wie kann ich Ihnen helfen?",
DefaultTopic: "Neues Gespräch",
BotHello: "Hallo! Wie kann ich Ihnen heute helfen?",
Error:
"Ein Fehler ist aufgetreten, bitte versuchen Sie es später noch einmal",
"Etwas ist schief gelaufen, bitte versuchen Sie es später noch einmal.",
Prompt: {
History: (content: string) =>
"Dies ist eine Zusammenfassung des bisherigen Chats als Hintergrundinformation: " +
"Dies ist eine Zusammenfassung des Chatverlaufs zwischen dem KI und dem Benutzer als Rückblick: " +
content,
Topic:
"Geben Sie ein kurzes Thema in vier bis fünf Wörtern zurück, ohne Erklärungen, ohne Satzzeichen, ohne Füllwörter, ohne zusätzliche Texte und ohne Fettdruck. Wenn kein Thema vorhanden ist, geben Sie bitte „Allgemeines Gespräch“ zurück.",
"Bitte erstellen Sie einen vier- bis fünfwörtigen Titel, der unser Gespräch zusammenfasst, ohne Einleitung, Zeichensetzung, Anführungszeichen, Punkte, Symbole oder zusätzlichen Text. Entfernen Sie Anführungszeichen.",
Summarize:
"Fassen Sie den Gesprächsinhalt zusammen, um als Kontextaufforderung für den nächsten Schritt zu dienen, halten Sie es unter 200 Zeichen",
"Fassen Sie unsere Diskussion kurz in 200 Wörtern oder weniger zusammen, um sie als Pronpt für zukünftige Gespräche zu verwenden.",
},
},
Copy: {
Success: "In die Zwischenablage geschrieben",
Success: "In die Zwischenablage kopiert",
Failed:
"Kopieren fehlgeschlagen, bitte erlauben Sie Zugriff auf die Zwischenablage",
},
Download: {
Success: "Inhalt wurde in Ihrem Verzeichnis heruntergeladen.",
Failed: "Download fehlgeschlagen.",
"Kopieren fehlgeschlagen, bitte geben Sie die Berechtigung zum Zugriff auf die Zwischenablage frei",
},
Context: {
Toast: (x: any) => `Beinhaltet ${x} vordefinierte Eingabeaufforderungen`,
Edit: "Aktuelle Gesprächseinstellungen",
Add: "Neues Gespräch hinzufügen",
Clear: "Kontext gelöscht",
Revert: "Kontext wiederherstellen",
Toast: (x: any) => `Mit ${x} Kontext-Prompts`,
Edit: "Kontext- und Gedächtnis-Prompts",
Add: "Hinzufügen",
},
Plugin: {
Name: "Plugins",
Name: "Plugin",
},
FineTuned: {
Sysmessage: "Du bist ein Assistent",
},
SearchChat: {
Name: "Suche",
Page: {
Title: "Chatverlauf durchsuchen",
Search: "Suchbegriff eingeben",
NoResult: "Keine Ergebnisse gefunden",
NoData: "Keine Daten",
Loading: "Laden",
SubTitle: (count: number) => `${count} Ergebnisse gefunden`,
},
Item: {
View: "Ansehen",
},
Sysmessage: "Du bist ein Assistent, der",
},
Mask: {
Name: "Masken",
Name: "Mask",
Page: {
Title: "Vordefinierte Rollenmasken",
SubTitle: (count: number) =>
`${count} vordefinierte Rollenbeschreibungen`,
Search: "Rollenmasken suchen",
Create: "Neu erstellen",
Title: "Prompt Template",
SubTitle: (count: number) => `${count} prompt templates`,
Search: "Search Templates",
Create: "Create",
},
Item: {
Info: (count: number) => `Beinhaltet ${count} vordefinierte Gespräche`,
Chat: "Gespräch",
View: "Anzeigen",
Edit: "Bearbeiten",
Delete: "Löschen",
DeleteConfirm: "Bestätigen Sie das Löschen?",
Info: (count: number) => `${count} prompts`,
Chat: "Chat",
View: "View",
Edit: "Edit",
Delete: "Delete",
DeleteConfirm: "Confirm to delete?",
},
EditModal: {
Title: (readonly: boolean) =>
`Vordefinierte Maske bearbeiten ${readonly ? "Nur lesen" : ""}`,
Download: "Vorgabe herunterladen",
Clone: "Vorgabe klonen",
`Edit Prompt Template ${readonly ? "(readonly)" : ""}`,
Download: "Download",
Clone: "Clone",
},
Config: {
Avatar: "Rollen-Avatar",
Name: "Rollenname",
Sync: {
Title: "Globale Einstellungen verwenden",
SubTitle:
"Soll das aktuelle Gespräch die globalen Modelleinstellungen verwenden?",
Confirm:
"Die benutzerdefinierten Einstellungen des aktuellen Gesprächs werden automatisch überschrieben. Bestätigen Sie, dass Sie die globalen Einstellungen aktivieren möchten?",
},
HideContext: {
Title: "Vordefinierte Gespräche ausblenden",
SubTitle:
"Nach dem Ausblenden werden vordefinierte Gespräche nicht mehr im Chat angezeigt",
},
Share: {
Title: "Diese Maske teilen",
SubTitle: "Generieren Sie einen Direktlink zu dieser Maske",
Action: "Link kopieren",
},
Avatar: "Bot Avatar",
Name: "Bot Name",
},
},
NewChat: {
Return: "Zurück",
Skip: "Direkt beginnen",
NotShow: "Nicht mehr anzeigen",
ConfirmNoShow:
"Bestätigen Sie die Deaktivierung? Nach der Deaktivierung können Sie jederzeit in den Einstellungen wieder aktivieren.",
Title: "Wählen Sie eine Maske aus",
SubTitle:
"Starten Sie jetzt und lassen Sie sich von den Gedanken hinter der Maske inspirieren",
More: "Alle anzeigen",
},
URLCommand: {
Code: "Ein Zugangscode wurde im Link gefunden. Möchten Sie diesen automatisch einfügen?",
Settings:
"Vordefinierte Einstellungen wurden im Link gefunden. Möchten Sie diese automatisch einfügen?",
Return: "Return",
Skip: "Skip",
Title: "Pick a Mask",
SubTitle: "Chat with the Soul behind the Mask",
More: "Find More",
NotShow: "Not Show Again",
ConfirmNoShow: "Confirm to disableYou can enable it in settings later.",
},
UI: {
Confirm: "Bestätigen",
Cancel: "Abbrechen",
Close: "Schließen",
Create: "Neu erstellen",
Edit: "Bearbeiten",
Export: "Exportieren",
Import: "Importieren",
Sync: "Synchronisieren",
Config: "Konfigurieren",
Confirm: "Confirm",
Cancel: "Cancel",
Close: "Close",
Create: "Create",
Edit: "Edit",
},
Exporter: {
Description: {
Title: "Nur Nachrichten nach dem Löschen des Kontexts werden angezeigt",
},
Model: "Modell",
Messages: "Nachrichten",
Topic: "Thema",

View File

@@ -44,7 +44,6 @@ const en: LocaleType = {
PinToastAction: "View",
Delete: "Delete",
Edit: "Edit",
FullScreen: "FullScreen",
},
Commands: {
new: "Start a new chat",
@@ -83,14 +82,6 @@ const en: LocaleType = {
SaveAs: "Save as Mask",
},
IsContext: "Contextual Prompt",
ShortcutKey: {
Title: "Keyboard Shortcuts",
newChat: "Open New Chat",
focusInput: "Focus Input Field",
copyLastMessage: "Copy Last Reply",
copyLastCode: "Copy Last Code Block",
showShortcutKey: "Show Shortcuts",
},
},
Export: {
Title: "Export Messages",
@@ -115,10 +106,6 @@ const en: LocaleType = {
Toast: "Capturing Image...",
Modal: "Long press or right click to save image",
},
Artifacts: {
Title: "Share Artifacts",
Error: "Share Error",
},
},
Select: {
Search: "Search",
@@ -144,7 +131,6 @@ const en: LocaleType = {
Settings: {
Title: "Settings",
SubTitle: "All Settings",
ShowPassword: "ShowPassword",
Danger: {
Reset: {
Title: "Reset All Settings",
@@ -168,12 +154,6 @@ const en: LocaleType = {
Title: "Font Size",
SubTitle: "Adjust font size of chat content",
},
FontFamily: {
Title: "Chat Font Family",
SubTitle:
"Font Family of the chat content, leave empty to apply global default font",
Placeholder: "Font Family Name",
},
InjectSystemPrompts: {
Title: "Inject System Prompts",
SubTitle: "Inject a global system prompt for every request",
@@ -316,7 +296,7 @@ const en: LocaleType = {
Endpoint: {
Title: "OpenAI Endpoint",
SubTitle: "Must start with http(s):// or use /api/openai as default",
SubTitle: "Must starts with http(s):// or use /api/openai as default",
},
},
Azure: {
@@ -346,7 +326,7 @@ const en: LocaleType = {
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
SubTitle: "Example:",
},
ApiVerion: {
@@ -354,98 +334,6 @@ const en: LocaleType = {
SubTitle: "Select and input a specific API version",
},
},
Baidu: {
ApiKey: {
Title: "Baidu API Key",
SubTitle: "Use a custom Baidu API Key",
Placeholder: "Baidu API Key",
},
SecretKey: {
Title: "Baidu Secret Key",
SubTitle: "Use a custom Baidu Secret Key",
Placeholder: "Baidu Secret Key",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "not supported, configure in .env",
},
},
Tencent: {
ApiKey: {
Title: "Tencent API Key",
SubTitle: "Use a custom Tencent API Key",
Placeholder: "Tencent API Key",
},
SecretKey: {
Title: "Tencent Secret Key",
SubTitle: "Use a custom Tencent Secret Key",
Placeholder: "Tencent Secret Key",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "not supported, configure in .env",
},
},
ByteDance: {
ApiKey: {
Title: "ByteDance API Key",
SubTitle: "Use a custom ByteDance API Key",
Placeholder: "ByteDance API Key",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
},
},
Alibaba: {
ApiKey: {
Title: "Alibaba API Key",
SubTitle: "Use a custom Alibaba Cloud API Key",
Placeholder: "Alibaba Cloud API Key",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
},
},
Moonshot: {
ApiKey: {
Title: "Moonshot API Key",
SubTitle: "Use a custom Moonshot API Key",
Placeholder: "Moonshot API Key",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
},
},
Stability: {
ApiKey: {
Title: "Stability API Key",
SubTitle: "Use a custom Stability API Key",
Placeholder: "Stability API Key",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
},
},
Iflytek: {
ApiKey: {
Title: "Iflytek API Key",
SubTitle: "Use a Iflytek API Key",
Placeholder: "Iflytek API Key",
},
ApiSecret: {
Title: "Iflytek API Secret",
SubTitle: "Use a Iflytek API Secret",
Placeholder: "Iflytek API Secret",
},
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
},
},
CustomModel: {
Title: "Custom Models",
SubTitle: "Custom model options, seperated by comma",
@@ -459,17 +347,13 @@ const en: LocaleType = {
Endpoint: {
Title: "Endpoint Address",
SubTitle: "Example: ",
SubTitle: "Example:",
},
ApiVersion: {
Title: "API Version (specific to gemini-pro)",
SubTitle: "Select a specific API version",
},
GoogleSafetySettings: {
Title: "Google Safety Settings",
SubTitle: "Select a safety filtering level",
},
},
},
@@ -525,68 +409,12 @@ const en: LocaleType = {
Clear: "Context Cleared",
Revert: "Revert",
},
Discovery: {
Name: "Discovery",
Plugin: {
Name: "Plugin",
},
FineTuned: {
Sysmessage: "You are an assistant that",
},
SearchChat: {
Name: "Search",
Page: {
Title: "Search Chat History",
Search: "Enter search query to search chat history",
NoResult: "No results found",
NoData: "No data",
Loading: "Loading...",
SubTitle: (count: number) => `Found ${count} results`,
},
Item: {
View: "View",
},
},
Plugin: {
Name: "Plugin",
Page: {
Title: "Plugins",
SubTitle: (count: number) => `${count} plugins`,
Search: "Search Plugin",
Create: "Create",
Find: "You can find awesome plugins on github: ",
},
Item: {
Info: (count: number) => `${count} method`,
View: "View",
Edit: "Edit",
Delete: "Delete",
DeleteConfirm: "Confirm to delete?",
},
Auth: {
None: "None",
Basic: "Basic",
Bearer: "Bearer",
Custom: "Custom",
CustomHeader: "Parameter Name",
Token: "Token",
Proxy: "Using Proxy",
ProxyDescription: "Using proxies to solve CORS error",
Location: "Location",
LocationHeader: "Header",
LocationQuery: "Query",
LocationBody: "Body",
},
EditModal: {
Title: (readonly: boolean) =>
`Edit Plugin ${readonly ? "(readonly)" : ""}`,
Download: "Download",
Auth: "Authentication Type",
Content: "OpenAPI Schema",
Load: "Load From URL",
Method: "Method",
Error: "OpenAPI Schema Error",
},
},
Mask: {
Name: "Mask",
Page: {
@@ -621,10 +449,6 @@ const en: LocaleType = {
Title: "Hide Context Prompts",
SubTitle: "Do not show in-context prompts in chat",
},
Artifacts: {
Title: "Enable Artifacts",
SubTitle: "Can render HTML page when enable artifacts.",
},
Share: {
Title: "Share This Mask",
SubTitle: "Generate a link to this mask",
@@ -662,65 +486,11 @@ const en: LocaleType = {
Topic: "Topic",
Time: "Time",
},
URLCommand: {
Code: "Detected access code from url, confirm to apply? ",
Settings: "Detected settings from url, confirm to apply?",
},
SdPanel: {
Prompt: "Prompt",
NegativePrompt: "Negative Prompt",
PleaseInput: (name: string) => `Please input ${name}`,
AspectRatio: "Aspect Ratio",
ImageStyle: "Image Style",
OutFormat: "Output Format",
AIModel: "AI Model",
ModelVersion: "Model Version",
Submit: "Submit",
ParamIsRequired: (name: string) => `${name} is required`,
Styles: {
D3Model: "3d-model",
AnalogFilm: "analog-film",
Anime: "anime",
Cinematic: "cinematic",
ComicBook: "comic-book",
DigitalArt: "digital-art",
Enhance: "enhance",
FantasyArt: "fantasy-art",
Isometric: "isometric",
LineArt: "line-art",
LowPoly: "low-poly",
ModelingCompound: "modeling-compound",
NeonPunk: "neon-punk",
Origami: "origami",
Photographic: "photographic",
PixelArt: "pixel-art",
TileTexture: "tile-texture",
},
},
Sd: {
SubTitle: (count: number) => `${count} images`,
Actions: {
Params: "See Params",
Copy: "Copy Prompt",
Delete: "Delete",
Retry: "Retry",
ReturnHome: "Return Home",
History: "History",
},
EmptyRecord: "No images yet",
Status: {
Name: "Status",
Success: "Success",
Error: "Error",
Wait: "Waiting",
Running: "Running",
},
Danger: {
Delete: "Confirm to delete?",
},
GenerateParams: "Generate Params",
Detail: "Detail",
},
};
export default en;

View File

@@ -1,580 +1,239 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const es: PartialLocaleType = {
WIP: "En construcción...",
Error: {
Unauthorized: isApp
? "Se detectó una clave API inválida. Por favor, ve a la página de [Configuración](/#/settings) para verificar si la clave API está configurada correctamente."
: "La contraseña de acceso es incorrecta o está vacía. Por favor, ve a la página de [Iniciar sesión](/#/auth) para ingresar la contraseña correcta, o en la página de [Configuración](/#/settings) para introducir tu propia clave API de OpenAI.",
},
Auth: {
Title: "Se requiere contraseña",
Tips: "El administrador ha habilitado la verificación de contraseña. Introduce el código de acceso a continuación",
SubTips: "O ingresa tu clave API de OpenAI o Google",
Input: "Introduce el código de acceso aquí",
Confirm: "Confirmar",
Later: "Más tarde",
Unauthorized:
"Acceso no autorizado, por favor ingrese el código de acceso en la [página](/#/auth) de configuración.",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} conversaciones`,
ChatItemCount: (count: number) => `${count} mensajes`,
},
Chat: {
SubTitle: (count: number) => `Total de ${count} conversaciones`,
EditMessage: {
Title: "Editar registro de mensajes",
Topic: {
Title: "Tema de la conversación",
SubTitle: "Cambiar el tema de la conversación actual",
},
},
SubTitle: (count: number) => `${count} mensajes con ChatGPT`,
Actions: {
ChatList: "Ver lista de mensajes",
CompressedHistory: "Ver historial de Prompts comprimidos",
Export: "Exportar historial de chat",
ChatList: "Ir a la lista de chats",
CompressedHistory: "Historial de memoria comprimido",
Export: "Exportar todos los mensajes como Markdown",
Copy: "Copiar",
Stop: "Detener",
Retry: "Reintentar",
Pin: "Fijar",
PinToastContent:
"Se ha fijado 1 conversación a los prompts predeterminados",
PinToastAction: "Ver",
Delete: "Eliminar",
Edit: "Editar",
Delete: "Delete",
},
Commands: {
new: "Nueva conversación",
newm: "Nueva conversación desde la máscara",
next: "Siguiente conversación",
prev: "Conversación anterior",
clear: "Limpiar contexto",
del: "Eliminar conversación",
},
InputActions: {
Stop: "Detener respuesta",
ToBottom: "Ir al más reciente",
Theme: {
auto: "Tema automático",
light: "Modo claro",
dark: "Modo oscuro",
},
Prompt: "Comandos rápidos",
Masks: "Todas las máscaras",
Clear: "Limpiar chat",
Settings: "Configuración de conversación",
UploadImage: "Subir imagen",
},
Rename: "Renombrar conversación",
Typing: "Escribiendo…",
Rename: "Renombrar chat",
Typing: "Escribiendo...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} para enviar`;
var inputHints = `Escribe algo y presiona ${submitKey} para enviar`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter para nueva línea";
inputHints += ", presiona Shift + Enter para nueva línea";
}
return (
inputHints + "/ para activar autocompletado: para activar comandos"
);
return inputHints;
},
Send: "Enviar",
Config: {
Reset: "Borrar memoria",
SaveAs: "Guardar como máscara",
Reset: "Reset to Default",
SaveAs: "Save as Mask",
},
IsContext: "Prompt predeterminado",
},
Export: {
Title: "Compartir historial de chat",
Title: "Todos los mensajes",
Copy: "Copiar todo",
Download: "Descargar archivo",
Share: "Compartir en ShareGPT",
MessageFromYou: "Usuario",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Formato de exportación",
SubTitle: "Puedes exportar como texto Markdown o imagen PNG",
},
IncludeContext: {
Title: "Incluir contexto de máscara",
SubTitle: "Mostrar contexto de máscara en los mensajes",
},
Steps: {
Select: "Seleccionar",
Preview: "Vista previa",
},
Image: {
Toast: "Generando captura de pantalla",
Modal: "Mantén presionado o haz clic derecho para guardar la imagen",
},
},
Select: {
Search: "Buscar mensajes",
All: "Seleccionar todo",
Latest: "Últimos mensajes",
Clear: "Limpiar selección",
Download: "Descargar",
MessageFromYou: "Mensaje de ti",
MessageFromChatGPT: "Mensaje de ChatGPT",
},
Memory: {
Title: "Resumen histórico",
EmptyContent:
"El contenido de la conversación es demasiado corto para resumir",
Send: "Comprimir automáticamente el historial de chat y enviarlo como contexto",
Copy: "Copiar resumen",
Reset: "[no usado]",
ResetConfirm: "¿Confirmar para borrar el resumen histórico?",
Title: "Historial de memoria",
EmptyContent: "Aún no hay nada.",
Copy: "Copiar todo",
Send: "Send Memory",
Reset: "Reset Session",
ResetConfirm:
"Resetting will clear the current conversation history and historical memory. Are you sure you want to reset?",
},
Home: {
NewChat: "Nueva conversación",
DeleteChat: "¿Confirmar la eliminación de la conversación seleccionada?",
DeleteToast: "Conversación eliminada",
Revert: "Deshacer",
NewChat: "Nuevo chat",
DeleteChat: "¿Confirmar eliminación de la conversación seleccionada?",
DeleteToast: "Chat Deleted",
Revert: "Revert",
},
Settings: {
Title: "Configuración",
SubTitle: "Todas las opciones de configuración",
SubTitle: "Todas las configuraciones",
Danger: {
Reset: {
Title: "Restablecer todas las configuraciones",
SubTitle:
"Restablecer todas las configuraciones a los valores predeterminados",
Action: "Restablecer ahora",
Confirm: "¿Confirmar el restablecimiento de todas las configuraciones?",
},
Clear: {
Title: "Eliminar todos los datos",
SubTitle: "Eliminar todos los chats y datos de configuración",
Action: "Eliminar ahora",
Confirm:
"¿Confirmar la eliminación de todos los chats y datos de configuración?",
},
},
Lang: {
Name: "Language", // ATENCIÓN: si deseas agregar una nueva traducción, por favor no traduzcas este valor, déjalo como `Language`
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Todos los idiomas",
},
Avatar: "Avatar",
FontSize: {
Title: "Tamaño de fuente",
SubTitle: "Tamaño de la fuente del contenido del chat",
},
FontFamily: {
Title: "Fuente del Chat",
SubTitle:
"Fuente del contenido del chat, dejar vacío para aplicar la fuente predeterminada global",
Placeholder: "Nombre de la Fuente",
SubTitle: "Ajustar el tamaño de fuente del contenido del chat",
},
InjectSystemPrompts: {
Title: "Inyectar mensajes del sistema",
Title: "Inyectar Prompts del Sistema",
SubTitle:
"Forzar la adición de un mensaje del sistema simulado de ChatGPT al principio de cada lista de mensajes",
"Agregar forzosamente un prompt de sistema simulado de ChatGPT al comienzo de la lista de mensajes en cada solicitud",
},
InputTemplate: {
Title: "Preprocesamiento de entrada del usuario",
SubTitle: "El último mensaje del usuario se rellenará en esta plantilla",
},
Update: {
Version: (x: string) => `Versión actual: ${x}`,
IsLatest: "Ya estás en la última versión",
Version: (x: string) => `Versión: ${x}`,
IsLatest: "Última versión",
CheckUpdate: "Buscar actualizaciones",
IsChecking: "Buscando actualizaciones...",
FoundUpdate: (x: string) => `Nueva versión encontrada: ${x}`,
GoToUpdate: "Ir a actualizar",
FoundUpdate: (x: string) => `Se encontró una nueva versión: ${x}`,
GoToUpdate: "Actualizar",
},
SendKey: "Tecla de enviar",
SendKey: "Tecla de envío",
Theme: "Tema",
TightBorder: "Modo sin borde",
TightBorder: "Borde ajustado",
SendPreviewBubble: {
Title: "Vista previa del globo",
SubTitle:
"Previsualiza el contenido Markdown en un globo de vista previa",
},
AutoGenerateTitle: {
Title: "Generar título automáticamente",
SubTitle: "Generar un título adecuado basado en el contenido del chat",
},
Sync: {
CloudState: "Datos en la nube",
NotSyncYet: "Aún no se ha sincronizado",
Success: "Sincronización exitosa",
Fail: "Sincronización fallida",
Config: {
Modal: {
Title: "Configurar sincronización en la nube",
Check: "Verificar disponibilidad",
},
SyncType: {
Title: "Tipo de sincronización",
SubTitle: "Selecciona el servidor de sincronización preferido",
},
Proxy: {
Title: "Habilitar proxy",
SubTitle:
"Debes habilitar el proxy para sincronizar en el navegador y evitar restricciones de CORS",
},
ProxyUrl: {
Title: "Dirección del proxy",
SubTitle: "Solo para el proxy CORS incluido en este proyecto",
},
WebDav: {
Endpoint: "Dirección WebDAV",
UserName: "Nombre de usuario",
Password: "Contraseña",
},
UpStash: {
Endpoint: "URL de REST de UpStash Redis",
UserName: "Nombre de respaldo",
Password: "Token de REST de UpStash Redis",
},
},
LocalState: "Datos locales",
Overview: (overview: any) => {
return `${overview.chat} conversaciones, ${overview.message} mensajes, ${overview.prompt} prompts, ${overview.mask} máscaras`;
},
ImportFailed: "Importación fallida",
Title: "Enviar burbuja de vista previa",
SubTitle: "Preview markdown in bubble",
},
Mask: {
Splash: {
Title: "Pantalla de inicio de máscara",
SubTitle:
"Mostrar la pantalla de inicio de la máscara al iniciar un nuevo chat",
},
Builtin: {
Title: "Ocultar máscaras integradas",
SubTitle:
"Ocultar las máscaras integradas en todas las listas de máscaras",
Title: "Mask Splash Screen",
SubTitle: "Show a mask splash screen before starting new chat",
},
},
Prompt: {
Disable: {
Title: "Deshabilitar autocompletado de prompts",
SubTitle:
"Escribe / al principio del campo de entrada para activar el autocompletado",
Title: "Desactivar autocompletado",
SubTitle: "Escribe / para activar el autocompletado",
},
List: "Lista de prompts personalizados",
List: "Lista de autocompletado",
ListCount: (builtin: number, custom: number) =>
`Integrados ${builtin}, definidos por el usuario ${custom}`,
`${builtin} incorporado, ${custom} definido por el usuario`,
Edit: "Editar",
Modal: {
Title: "Lista de prompts",
Add: "Nuevo",
Search: "Buscar prompts",
Title: "Prompt List",
Add: "Add One",
Search: "Search Prompts",
},
EditModal: {
Title: "Editar prompt",
Title: "Edit Prompt",
},
},
HistoryCount: {
Title: "Número de mensajes históricos adjuntos",
SubTitle: "Número de mensajes históricos enviados con cada solicitud",
Title: "Cantidad de mensajes adjuntos",
SubTitle: "Número de mensajes enviados adjuntos por solicitud",
},
CompressThreshold: {
Title: "Umbral de compresión de mensajes históricos",
Title: "Umbral de compresión de historial",
SubTitle:
"Cuando los mensajes históricos no comprimidos superan este valor, se realizará la compresión",
"Se comprimirán los mensajes si la longitud de los mensajes no comprimidos supera el valor",
},
Usage: {
Title: "Consulta de saldo",
Title: "Saldo de la cuenta",
SubTitle(used: any, total: any) {
return `Saldo usado este mes: $${used}, total suscrito: $${total}`;
return `Usado $${used}, subscription $${total}`;
},
IsChecking: "Verificando",
Check: "Revisar de nuevo",
NoAccess:
"Introduce la clave API o la contraseña de acceso para ver el saldo",
IsChecking: "Comprobando...",
Check: "Comprobar de nuevo",
NoAccess: "Introduzca la clave API para comprobar el saldo",
},
Access: {
AccessCode: {
Title: "Contraseña de acceso",
SubTitle: "El administrador ha habilitado el acceso encriptado",
Placeholder: "Introduce la contraseña de acceso",
},
CustomEndpoint: {
Title: "Interfaz personalizada",
SubTitle: "¿Usar servicios personalizados de Azure u OpenAI?",
},
Provider: {
Title: "Proveedor de modelos",
SubTitle: "Cambiar entre diferentes proveedores",
},
OpenAI: {
ApiKey: {
Title: "Clave API",
SubTitle:
"Usa una clave API de OpenAI personalizada para omitir la restricción de acceso por contraseña",
Placeholder: "Clave API de OpenAI",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle:
"Debe incluir http(s):// además de la dirección predeterminada",
},
},
Azure: {
ApiKey: {
Title: "Clave de interfaz",
SubTitle:
"Usa una clave de Azure personalizada para omitir la restricción de acceso por contraseña",
Placeholder: "Clave API de Azure",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle: "Ejemplo:",
},
ApiVerion: {
Title: "Versión de la interfaz (versión de api de azure)",
SubTitle: "Selecciona una versión específica",
},
},
Anthropic: {
ApiKey: {
Title: "Clave de interfaz",
SubTitle:
"Usa una clave de Anthropic personalizada para omitir la restricción de acceso por contraseña",
Placeholder: "Clave API de Anthropic",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle: "Ejemplo:",
},
ApiVerion: {
Title: "Versión de la interfaz (versión de claude api)",
SubTitle: "Selecciona una versión específica de la API",
},
},
Google: {
ApiKey: {
Title: "Clave API",
SubTitle: "Obtén tu clave API de Google AI",
Placeholder: "Introduce tu clave API de Google AI Studio",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle: "Ejemplo:",
},
ApiVersion: {
Title: "Versión de la API (solo para gemini-pro)",
SubTitle: "Selecciona una versión específica de la API",
},
GoogleSafetySettings: {
Title: "Nivel de filtrado de seguridad de Google",
SubTitle: "Configura el nivel de filtrado de contenido",
},
},
Baidu: {
ApiKey: {
Title: "Clave API",
SubTitle: "Usa una clave API de Baidu personalizada",
Placeholder: "Clave API de Baidu",
},
SecretKey: {
Title: "Clave secreta",
SubTitle: "Usa una clave secreta de Baidu personalizada",
Placeholder: "Clave secreta de Baidu",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle:
"No admite personalización, dirígete a .env para configurarlo",
},
},
ByteDance: {
ApiKey: {
Title: "Clave de interfaz",
SubTitle: "Usa una clave API de ByteDance personalizada",
Placeholder: "Clave API de ByteDance",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle: "Ejemplo:",
},
},
Alibaba: {
ApiKey: {
Title: "Clave de interfaz",
SubTitle: "Usa una clave API de Alibaba Cloud personalizada",
Placeholder: "Clave API de Alibaba Cloud",
},
Endpoint: {
Title: "Dirección del endpoint",
SubTitle: "Ejemplo:",
},
},
CustomModel: {
Title: "Nombre del modelo personalizado",
SubTitle:
"Agrega opciones de modelos personalizados, separados por comas",
},
},
Model: "Modelo (model)",
Model: "Modelo",
Temperature: {
Title: "Aleatoriedad (temperature)",
SubTitle: "Cuanto mayor sea el valor, más aleatorio será el resultado",
},
TopP: {
Title: "Muestreo por núcleo (top_p)",
SubTitle: "Similar a la aleatoriedad, pero no cambies ambos a la vez",
Title: "Temperatura",
SubTitle: "Un valor mayor genera una salida más aleatoria",
},
MaxTokens: {
Title: "Límite de tokens por respuesta (max_tokens)",
SubTitle: "Número máximo de tokens utilizados en una sola interacción",
Title: "Máximo de tokens",
SubTitle: "Longitud máxima de tokens de entrada y tokens generados",
},
PresencePenalty: {
Title: "Novedad de temas (presence_penalty)",
Title: "Penalización de presencia",
SubTitle:
"Cuanto mayor sea el valor, más probable es que se amplíen a nuevos temas",
"Un valor mayor aumenta la probabilidad de hablar sobre nuevos temas",
},
FrequencyPenalty: {
Title: "Penalización de frecuencia (frequency_penalty)",
Title: "Penalización de frecuencia",
SubTitle:
"Cuanto mayor sea el valor, más probable es que se reduzcan las palabras repetidas",
"Un valor mayor que disminuye la probabilidad de repetir la misma línea",
},
},
Store: {
DefaultTopic: "Nuevo chat",
BotHello: "¿En qué puedo ayudarte?",
Error: "Hubo un error, inténtalo de nuevo más tarde",
DefaultTopic: "Nueva conversación",
BotHello: "¡Hola! ¿Cómo puedo ayudarte hoy?",
Error: "Algo salió mal, por favor intenta nuevamente más tarde.",
Prompt: {
History: (content: string) =>
"Este es un resumen del chat histórico como referencia: " + content,
"Este es un resumen del historial del chat entre la IA y el usuario como recapitulación: " +
content,
Topic:
"Devuelve un tema breve de esta frase en cuatro a cinco palabras, sin explicación, sin puntuación, sin muletillas, sin texto adicional, sin negritas. Si no hay tema, devuelve 'charlas casuales'",
"Por favor, genera un título de cuatro a cinco palabras que resuma nuestra conversación sin ningún inicio, puntuación, comillas, puntos, símbolos o texto adicional. Elimina las comillas que lo envuelven.",
Summarize:
"Resume brevemente el contenido de la conversación para usar como un prompt de contexto, manteniéndolo dentro de 200 palabras",
"Resuma nuestra discusión brevemente en 200 caracteres o menos para usarlo como un recordatorio para futuros contextos.",
},
},
Copy: {
Success: "Copiado al portapapeles",
Failed: "Error al copiar, por favor otorga permisos al portapapeles",
},
Download: {
Success: "Contenido descargado en tu directorio.",
Failed: "Error al descargar.",
Failed:
"La copia falló, por favor concede permiso para acceder al portapapeles",
},
Context: {
Toast: (x: any) => `Contiene ${x} prompts predefinidos`,
Edit: "Configuración del chat actual",
Add: "Agregar una conversación",
Clear: "Contexto borrado",
Revert: "Restaurar contexto",
Toast: (x: any) => `With ${x} contextual prompts`,
Edit: "Contextual and Memory Prompts",
Add: "Add One",
},
Plugin: {
Name: "Complemento",
Name: "Plugin",
},
FineTuned: {
Sysmessage: "Eres un asistente",
},
SearchChat: {
Name: "Buscar",
Page: {
Title: "Buscar en el historial de chat",
Search: "Ingrese la palabra clave de búsqueda",
NoResult: "No se encontraron resultados",
NoData: "Sin datos",
Loading: "Cargando",
SubTitle: (count: number) => `Se encontraron ${count} resultados`,
},
Item: {
View: "Ver",
},
Sysmessage: "Eres un asistente que",
},
Mask: {
Name: "Máscara",
Name: "Mask",
Page: {
Title: "Máscaras de rol predefinidas",
SubTitle: (count: number) => `${count} definiciones de rol predefinidas`,
Search: "Buscar máscara de rol",
Create: "Crear nuevo",
Title: "Prompt Template",
SubTitle: (count: number) => `${count} prompt templates`,
Search: "Search Templates",
Create: "Create",
},
Item: {
Info: (count: number) => `Contiene ${count} conversaciones predefinidas`,
Info: (count: number) => `${count} prompts`,
Chat: "Chat",
View: "Ver",
Edit: "Editar",
Delete: "Eliminar",
DeleteConfirm: "¿Confirmar eliminación?",
View: "View",
Edit: "Edit",
Delete: "Delete",
DeleteConfirm: "Confirm to delete?",
},
EditModal: {
Title: (readonly: boolean) =>
`Editar máscara predefinida ${readonly ? "solo lectura" : ""}`,
Download: "Descargar predefinido",
Clone: "Clonar predefinido",
`Edit Prompt Template ${readonly ? "(readonly)" : ""}`,
Download: "Download",
Clone: "Clone",
},
Config: {
Avatar: "Avatar del rol",
Name: "Nombre del rol",
Sync: {
Title: "Usar configuración global",
SubTitle:
"¿Usar la configuración global del modelo para la conversación actual?",
Confirm:
"La configuración personalizada de la conversación actual se sobrescribirá automáticamente, ¿confirmar habilitar la configuración global?",
},
HideContext: {
Title: "Ocultar conversaciones predefinidas",
SubTitle:
"Las conversaciones predefinidas ocultas no aparecerán en la interfaz de chat",
},
Share: {
Title: "Compartir esta máscara",
SubTitle: "Generar un enlace directo a esta máscara",
Action: "Copiar enlace",
},
Avatar: "Bot Avatar",
Name: "Bot Name",
},
},
NewChat: {
Return: "Regresar",
Skip: "Comenzar ahora",
NotShow: "No mostrar más",
ConfirmNoShow:
"¿Confirmar desactivación? Puedes reactivar en la configuración en cualquier momento.",
Title: "Selecciona una máscara",
SubTitle: "Comienza ahora y colisiona con la mente detrás de la máscara",
More: "Ver todo",
},
URLCommand: {
Code: "Detectado un código de acceso en el enlace, ¿deseas autocompletarlo?",
Settings:
"Detectada configuración predefinida en el enlace, ¿deseas autocompletarla?",
Return: "Return",
Skip: "Skip",
Title: "Pick a Mask",
SubTitle: "Chat with the Soul behind the Mask",
More: "Find More",
NotShow: "Not Show Again",
ConfirmNoShow: "Confirm to disableYou can enable it in settings later.",
},
UI: {
Confirm: "Confirmar",
Cancel: "Cancelar",
Close: "Cerrar",
Create: "Crear",
Edit: "Editar",
Export: "Exportar",
Import: "Importar",
Sync: "Sincronizar",
Config: "Configurar",
Confirm: "Confirm",
Cancel: "Cancel",
Close: "Close",
Create: "Create",
Edit: "Edit",
},
Exporter: {
Description: {
Title: "Solo se mostrarán los mensajes después de borrar el contexto",
},
Model: "Modelo",
Messages: "Mensajes",
Topic: "Tema",
Time: "Hora",
Time: "Time",
},
};

View File

@@ -1,559 +1,294 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const fr: PartialLocaleType = {
WIP: "Prochainement...",
Error: {
Unauthorized: isApp
? "Clé API invalide détectée. Veuillez vérifier si la clé API est correctement configurée dans la page [Paramètres](/#/settings)."
: "Le mot de passe d'accès est incorrect ou manquant. Veuillez entrer le mot de passe d'accès correct sur la page [Connexion](/#/auth) ou entrer votre propre clé API OpenAI sur la page [Paramètres](/#/settings).",
},
Auth: {
Title: "Mot de passe requis",
Tips: "L'administrateur a activé la vérification par mot de passe. Veuillez entrer le code d'accès ci-dessous",
SubTips: "Ou entrez votre clé API OpenAI ou Google",
Input: "Entrez le code d'accès ici",
Confirm: "Confirmer",
Later: "Plus tard",
Unauthorized:
"Accès non autorisé, veuillez saisir le code d'accès dans la [page](/#/auth) des paramètres.",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} conversations`,
ChatItemCount: (count: number) => `${count} messages en total`,
},
Chat: {
SubTitle: (count: number) => `Total de ${count} conversations`,
EditMessage: {
Title: "Modifier l'historique des messages",
Topic: {
Title: "Sujet de la discussion",
SubTitle: "Modifier le sujet de la discussion actuel",
},
},
SubTitle: (count: number) => `${count} messages échangés avec ChatGPT`,
Actions: {
ChatList: "Voir la liste des messages",
CompressedHistory: "Voir l'historique des prompts compressés",
Export: "Exporter l'historique de la discussion",
ChatList: "Aller à la liste de discussion",
CompressedHistory: "Mémoire d'historique compressée Prompt",
Export: "Exporter tous les messages en tant que Markdown",
Copy: "Copier",
Stop: "Arrêter",
Retry: "Réessayer",
Pin: "Épingler",
PinToastContent: "1 conversation épinglée aux prompts prédéfinis",
PinToastAction: "Voir",
Delete: "Supprimer",
Pin: "Épingler",
PinToastContent: "Épingler 2 messages à des messages contextuels",
PinToastAction: "Voir",
Edit: "Modifier",
},
Commands: {
new: "Nouvelle discussion",
newm: "Créer une discussion à partir du masque",
next: "Discussion suivante",
prev: "Discussion précédente",
new: "Commencer une nouvelle conversation",
newm: "Démarrer une nouvelle conversation avec un assistant",
next: "Conversation suivante",
prev: "Conversation précédente",
clear: "Effacer le contexte",
del: "Supprimer la discussion",
del: "Supprimer la Conversation",
},
InputActions: {
Stop: "Arrêter la réponse",
ToBottom: "Aller au plus récent",
Stop: "Stop",
ToBottom: "Au dernier",
Theme: {
auto: "Thème automatique",
light: "Mode clair",
dark: "Mode sombre",
auto: "Auto",
light: "Thème clair",
dark: "Thème sombre",
},
Prompt: "Commandes rapides",
Masks: "Tous les masques",
Clear: "Effacer la discussion",
Settings: "Paramètres de la discussion",
UploadImage: "Télécharger une image",
Prompt: "Instructions",
Masks: "Assistants",
Clear: "Effacer le contexte",
Settings: "Réglages",
},
Rename: "Renommer la discussion",
Rename: "Renommer la conversation",
Typing: "En train d'écrire…",
Input: (submitKey: string) => {
var inputHints = `${submitKey} pour envoyer`;
var inputHints = `Appuyez sur ${submitKey} pour envoyer`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter pour passer à la ligne";
inputHints += ", Shift + Enter pour insérer un saut de ligne";
}
return inputHints + "/ pour compléter, : pour déclencher des commandes";
return inputHints + ", / pour rechercher des prompts";
},
Send: "Envoyer",
Config: {
Reset: "Effacer la mémoire",
SaveAs: "Enregistrer comme masque",
Reset: "Restaurer les paramètres par défaut",
SaveAs: "Enregistrer en tant que masque",
},
IsContext: "Prompt prédéfini",
},
Export: {
Title: "Partager l'historique des discussions",
Copy: "Tout copier",
Download: "Télécharger le fichier",
Share: "Partager sur ShareGPT",
MessageFromYou: "Utilisateur",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Format d'exportation",
SubTitle: "Vous pouvez exporter en texte Markdown ou en image PNG",
},
IncludeContext: {
Title: "Inclure le contexte du masque",
SubTitle: "Afficher le contexte du masque dans les messages",
},
Steps: {
Select: "Sélectionner",
Preview: "Aperçu",
},
Image: {
Toast: "Génération de la capture d'écran",
Modal:
"Appuyez longuement ou faites un clic droit pour enregistrer l'image",
},
},
Select: {
Search: "Rechercher des messages",
All: "Tout sélectionner",
Latest: "Derniers messages",
Clear: "Effacer la sélection",
Title: "Tous les messages",
Copy: "Tout sélectionner",
Download: "Télécharger",
MessageFromYou: "Message de votre part",
MessageFromChatGPT: "Message de ChatGPT",
},
Memory: {
Title: "Résumé historique",
EmptyContent: "Le contenu de la discussion est trop court pour être résumé",
Send: "Compresser automatiquement l'historique des discussions et l'envoyer comme contexte",
Copy: "Copier le résumé",
Reset: "[unused]",
ResetConfirm: "Confirmer la suppression du résumé historique ?",
Title: "Prompt mémoire",
EmptyContent: "Rien encore.",
Send: "Envoyer la mémoire",
Copy: "Copier la mémoire",
Reset: "Réinitialiser la session",
ResetConfirm:
"La réinitialisation supprimera l'historique de la conversation actuelle ainsi que la mémoire de l'historique. Êtes-vous sûr de vouloir procéder à la réinitialisation?",
},
Home: {
NewChat: "Nouvelle discussion",
DeleteChat: "Confirmer la suppression de la discussion sélectionnée ?",
DeleteToast: "Discussion supprimée",
Revert: "Annuler",
DeleteChat: "Confirmer la suppression de la conversation sélectionnée ?",
DeleteToast: "Conversation supprimée",
Revert: "Revenir en arrière",
},
Settings: {
Title: "Paramètres",
SubTitle: "Toutes les options de configuration",
SubTitle: "Toutes les configurations",
Danger: {
Reset: {
Title: "Réinitialiser tous les paramètres",
SubTitle:
"Réinitialiser toutes les options de configuration aux valeurs par défaut",
Action: "Réinitialiser maintenant",
Confirm: "Confirmer la réinitialisation de tous les paramètres ?",
Title: "Restaurer les paramètres",
SubTitle: "Restaurer les paramètres par défaut",
Action: "Reinitialiser",
Confirm: "Confirmer la réinitialisation des paramètres?",
},
Clear: {
Title: "Effacer toutes les données",
Title: "Supprimer toutes les données",
SubTitle:
"Effacer toutes les discussions et les données de configuration",
Action: "Effacer maintenant",
Confirm:
"Confirmer l'effacement de toutes les discussions et données de configuration ?",
"Effacer toutes les données, y compris les conversations et les paramètres",
Action: "Supprimer",
Confirm: "Confirmer la suppression de toutes les données?",
},
},
Lang: {
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
Name: "Language", // ATTENTION : si vous souhaitez ajouter une nouvelle traduction, ne traduisez pas cette valeur, laissez-la sous forme de `Language`
All: "Toutes les langues",
},
Avatar: "Avatar",
FontSize: {
Title: "Taille de la police",
SubTitle: "Taille de la police pour le contenu des discussions",
},
FontFamily: {
Title: "Police de Chat",
SubTitle:
"Police du contenu du chat, laissez vide pour appliquer la police par défaut globale",
Placeholder: "Nom de la Police",
Title: "Taille des polices",
SubTitle: "Ajuste la taille de police du contenu de la conversation",
},
InjectSystemPrompts: {
Title: "Injecter des invites système",
SubTitle:
"Ajouter de manière forcée une invite système simulée de ChatGPT au début de chaque liste de messages",
"Ajoute de force une invite système simulée de ChatGPT au début de la liste des messages pour chaque demande",
},
InputTemplate: {
Title: "Prétraitement des entrées utilisateur",
SubTitle:
"Le dernier message de l'utilisateur sera intégré dans ce modèle",
Title: "Template",
SubTitle: "Le message le plus récent sera ajouté à ce template.",
},
Update: {
Version: (x: string) => `Version actuelle : ${x}`,
IsLatest: "Vous avez la dernière version",
CheckUpdate: "Vérifier les mises à jour",
IsChecking: "Vérification des mises à jour en cours...",
FoundUpdate: (x: string) => `Nouvelle version trouvée : ${x}`,
GoToUpdate: "Aller à la mise à jour",
Version: (x: string) => `Version : ${x}`,
IsLatest: "Dernière version",
CheckUpdate: "Vérifier la mise à jour",
IsChecking: "Vérification de la mise à jour...",
FoundUpdate: (x: string) => `Nouvelle version disponible : ${x}`,
GoToUpdate: "Mise à jour",
},
SendKey: "Touche d'envoi",
SendKey: "Clé d'envoi",
Theme: "Thème",
TightBorder: "Mode sans bordure",
TightBorder: "Bordure serrée",
SendPreviewBubble: {
Title: "Bulle d'aperçu",
SubTitle: "Aperçu du contenu Markdown dans la bulle d'aperçu",
},
AutoGenerateTitle: {
Title: "Génération automatique de titres",
SubTitle:
"Générer un titre approprié en fonction du contenu de la discussion",
},
Sync: {
CloudState: "Données cloud",
NotSyncYet: "Pas encore synchronisé",
Success: "Synchronisation réussie",
Fail: "Échec de la synchronisation",
Config: {
Modal: {
Title: "Configurer la synchronisation cloud",
Check: "Vérifier la disponibilité",
},
SyncType: {
Title: "Type de synchronisation",
SubTitle: "Choisissez le serveur de synchronisation préféré",
},
Proxy: {
Title: "Activer le proxy",
SubTitle:
"Lors de la synchronisation dans le navigateur, le proxy doit être activé pour éviter les restrictions de domaine croisé",
},
ProxyUrl: {
Title: "Adresse du proxy",
SubTitle:
"Uniquement pour le proxy de domaine croisé fourni par le projet",
},
WebDav: {
Endpoint: "Adresse WebDAV",
UserName: "Nom d'utilisateur",
Password: "Mot de passe",
},
UpStash: {
Endpoint: "URL REST Redis UpStash",
UserName: "Nom de sauvegarde",
Password: "Token REST Redis UpStash",
},
},
LocalState: "Données locales",
Overview: (overview: any) => {
return `${overview.chat} discussions, ${overview.message} messages, ${overview.prompt} invites, ${overview.mask} masques`;
},
ImportFailed: "Échec de l'importation",
Title: "Aperçu de l'envoi dans une bulle",
SubTitle: "Aperçu du Markdown dans une bulle",
},
Mask: {
Splash: {
Title: "Page de démarrage du masque",
Title: "Écran de masque",
SubTitle:
"Afficher la page de démarrage du masque lors de la création d'une nouvelle discussion",
"Afficher un écran de masque avant de démarrer une nouvelle discussion",
},
Builtin: {
Title: "Masquer les masques intégrés",
SubTitle:
"Masquer les masques intégrés dans toutes les listes de masques",
Title: "Masquer Les Assistants Intégrés",
SubTitle: "Masquer les assistants intégrés par défaut",
},
},
Prompt: {
Disable: {
Title: "Désactiver la complétion automatique des invites",
SubTitle:
"Saisir / au début de la zone de texte pour déclencher la complétion automatique",
Title: "Désactiver la saisie semi-automatique",
SubTitle: "Appuyez sur / pour activer la saisie semi-automatique",
},
List: "Liste des invites personnalisées",
List: "Liste de prompts",
ListCount: (builtin: number, custom: number) =>
`${builtin} intégrées, ${custom} définies par l'utilisateur`,
`${builtin} intégré, ${custom} personnalisé`,
Edit: "Modifier",
Modal: {
Title: "Liste des invites",
Add: "Créer",
Search: "Rechercher des invites",
Title: "Liste de prompts",
Add: "Ajouter un élément",
Search: "Rechercher des prompts",
},
EditModal: {
Title: "Modifier les invites",
Title: "Modifier le prompt",
},
},
HistoryCount: {
Title: "Nombre de messages historiques",
SubTitle: "Nombre de messages historiques envoyés avec chaque demande",
Title: "Nombre de messages joints",
SubTitle: "Nombre de messages envoyés attachés par demande",
},
CompressThreshold: {
Title: "Seuil de compression des messages historiques",
Title: "Seuil de compression de l'historique",
SubTitle:
"Compresser les messages historiques lorsque leur longueur dépasse cette valeur",
"Comprimera si la longueur des messages non compressés dépasse cette valeur",
},
Usage: {
Title: "Vérification du solde",
Title: "Solde du compte",
SubTitle(used: any, total: any) {
return `Utilisé ce mois-ci : $${used}, Total d'abonnement : $${total}`;
},
IsChecking: "Vérification en cours…",
Check: "Re-vérifier",
NoAccess:
"Entrez la clé API ou le mot de passe d'accès pour vérifier le solde",
},
Access: {
AccessCode: {
Title: "Mot de passe d'accès",
SubTitle: "L'administrateur a activé l'accès sécurisé",
Placeholder: "Veuillez entrer le mot de passe d'accès",
},
CustomEndpoint: {
Title: "Interface personnalisée",
SubTitle: "Utiliser un service Azure ou OpenAI personnalisé",
},
Provider: {
Title: "Fournisseur de modèle",
SubTitle: "Changer de fournisseur de service",
},
OpenAI: {
ApiKey: {
Title: "Clé API",
SubTitle:
"Utiliser une clé OpenAI personnalisée pour contourner les restrictions d'accès par mot de passe",
Placeholder: "Clé API OpenAI",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle: "Doit inclure http(s):// en dehors de l'adresse par défaut",
},
},
Azure: {
ApiKey: {
Title: "Clé d'interface",
SubTitle:
"Utiliser une clé Azure personnalisée pour contourner les restrictions d'accès par mot de passe",
Placeholder: "Clé API Azure",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle: "Exemple :",
},
ApiVerion: {
Title: "Version de l'interface (version API azure)",
SubTitle: "Choisissez une version spécifique",
},
},
Anthropic: {
ApiKey: {
Title: "Clé d'interface",
SubTitle:
"Utiliser une clé Anthropic personnalisée pour contourner les restrictions d'accès par mot de passe",
Placeholder: "Clé API Anthropic",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle: "Exemple :",
},
ApiVerion: {
Title: "Version de l'interface (version API claude)",
SubTitle: "Choisissez une version spécifique de l'API",
},
},
Google: {
ApiKey: {
Title: "Clé API",
SubTitle: "Obtenez votre clé API Google AI",
Placeholder: "Entrez votre clé API Google AI Studio",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle: "Exemple :",
},
ApiVersion: {
Title: "Version de l'API (pour gemini-pro uniquement)",
SubTitle: "Choisissez une version spécifique de l'API",
},
GoogleSafetySettings: {
Title: "Niveau de filtrage de sécurité Google",
SubTitle: "Définir le niveau de filtrage du contenu",
},
},
Baidu: {
ApiKey: {
Title: "Clé API",
SubTitle: "Utiliser une clé API Baidu personnalisée",
Placeholder: "Clé API Baidu",
},
SecretKey: {
Title: "Clé secrète",
SubTitle: "Utiliser une clé secrète Baidu personnalisée",
Placeholder: "Clé secrète Baidu",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle:
"Non pris en charge pour les configurations personnalisées dans .env",
},
},
ByteDance: {
ApiKey: {
Title: "Clé d'interface",
SubTitle: "Utiliser une clé API ByteDance personnalisée",
Placeholder: "Clé API ByteDance",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle: "Exemple :",
},
},
Alibaba: {
ApiKey: {
Title: "Clé d'interface",
SubTitle: "Utiliser une clé API Alibaba Cloud personnalisée",
Placeholder: "Clé API Alibaba Cloud",
},
Endpoint: {
Title: "Adresse de l'interface",
SubTitle: "Exemple :",
},
},
CustomModel: {
Title: "Nom du modèle personnalisé",
SubTitle:
"Ajouter des options de modèles personnalisés, séparées par des virgules",
return `Épuisé ce mois-ci $${used}, abonnement $${total}`;
},
IsChecking: "Vérification...",
Check: "Vérifier",
NoAccess: "Entrez la clé API pour vérifier le solde",
},
Model: "Modèle",
Temperature: {
Title: "Aléatoire (temperature)",
SubTitle: "Plus la valeur est élevée, plus les réponses sont aléatoires",
Title: "Température",
SubTitle: "Une valeur plus élevée rendra les réponses plus aléatoires",
},
TopP: {
Title: "Échantillonnage par noyau (top_p)",
Title: "Top P",
SubTitle:
"Semblable à l'aléatoire, mais ne pas modifier en même temps que l'aléatoire",
"Ne modifiez pas à moins que vous ne sachiez ce que vous faites",
},
MaxTokens: {
Title: "Limite de réponse unique (max_tokens)",
SubTitle: "Nombre maximal de tokens utilisés pour une interaction unique",
Title: "Limite de Tokens",
SubTitle: "Longueur maximale des tokens d'entrée et des tokens générés",
},
PresencePenalty: {
Title: "Nouveauté du sujet (presence_penalty)",
Title: "Pénalité de présence",
SubTitle:
"Plus la valeur est élevée, plus il est probable d'élargir aux nouveaux sujets",
"Une valeur plus élevée augmentera la probabilité d'introduire de nouveaux sujets",
},
FrequencyPenalty: {
Title: "Pénalité de fréquence (frequency_penalty)",
Title: "Pénalité de fréquence",
SubTitle:
"Plus la valeur est élevée, plus il est probable de réduire les répétitions",
"Une valeur plus élevée diminuant la probabilité de répéter la même ligne",
},
},
Store: {
DefaultTopic: "Nouvelle discussion",
BotHello: "Comment puis-je vous aider ?",
Error: "Une erreur est survenue, veuillez réessayer plus tard",
DefaultTopic: "Nouvelle conversation",
BotHello: "Bonjour ! Comment puis-je vous aider aujourd'hui ?",
Error: "Quelque chose s'est mal passé, veuillez réessayer plus tard.",
Prompt: {
History: (content: string) =>
"Voici le résumé de la discussion précédente : " + content,
"Ceci est un résumé de l'historique des discussions entre l'IA et l'utilisateur : " +
content,
Topic:
"Utilisez quatre à cinq mots pour retourner le sujet succinct de cette phrase, sans explication, sans ponctuation, sans interjections, sans texte superflu, sans gras. Si aucun sujet, retournez simplement « discussion informelle »",
"Veuillez générer un titre de quatre à cinq mots résumant notre conversation sans introduction, ponctuation, guillemets, points, symboles ou texte supplémentaire. Supprimez les guillemets inclus.",
Summarize:
"Faites un résumé succinct de la discussion, à utiliser comme prompt de contexte ultérieur, en moins de 200 mots",
"Résumez brièvement nos discussions en 200 mots ou moins pour les utiliser comme prompt de contexte futur.",
},
},
Copy: {
Success: "Copié dans le presse-papiers",
Failed: "Échec de la copie, veuillez autoriser l'accès au presse-papiers",
},
Download: {
Success: "Le contenu a été téléchargé dans votre répertoire.",
Failed: "Échec du téléchargement.",
Failed:
"La copie a échoué, veuillez accorder l'autorisation d'accès au presse-papiers",
},
Context: {
Toast: (x: any) => `Contient ${x} invites prédéfinies`,
Edit: "Paramètres de la discussion actuelle",
Add: "Ajouter une discussion",
Clear: "Contexte effacé",
Revert: "Restaurer le contexte",
Toast: (x: any) => `Avec ${x} contextes de prompts`,
Edit: "Contextes et mémoires de prompts",
Add: "Ajouter un prompt",
},
Plugin: {
Name: "Plugin",
Name: "Extension",
},
FineTuned: {
Sysmessage: "Vous êtes un assistant",
},
SearchChat: {
Name: "Recherche",
Page: {
Title: "Rechercher dans l'historique des discussions",
Search: "Entrez le mot-clé de recherche",
NoResult: "Aucun résultat trouvé",
NoData: "Aucune donnée",
Loading: "Chargement",
SubTitle: (count: number) => `${count} résultats trouvés`,
},
Item: {
View: "Voir",
},
Sysmessage: "Eres un asistente que",
},
Mask: {
Name: "Masque",
Page: {
Title: "Masques de rôle prédéfinis",
SubTitle: (count: number) => `${count} définitions de rôle prédéfinies`,
Search: "Rechercher des masques de rôle",
Title: "Modèle de prompt",
SubTitle: (count: number) => `${count} modèles de prompts`,
Search: "Rechercher des modèles",
Create: "Créer",
},
Item: {
Info: (count: number) => `Contient ${count} discussions prédéfinies`,
Info: (count: number) => `${count} prompts`,
Chat: "Discussion",
View: "Voir",
View: "Vue",
Edit: "Modifier",
Delete: "Supprimer",
DeleteConfirm: "Confirmer la suppression ?",
DeleteConfirm: "Confirmer la suppression?",
},
EditModal: {
Title: (readonly: boolean) =>
`Modifier le masque prédéfini ${readonly ? " (lecture seule)" : ""}`,
Download: "Télécharger le masque",
Clone: "Cloner le masque",
`Modifier le modèle de prompt ${readonly ? "(en lecture seule)" : ""}`,
Download: "Télécharger",
Clone: "Dupliquer",
},
Config: {
Avatar: "Avatar du rôle",
Name: "Nom du rôle",
Avatar: "Avatar de lassistant",
Name: "Nom de lassistant",
Sync: {
Title: "Utiliser les paramètres globaux",
SubTitle:
"Cette discussion utilise-t-elle les paramètres du modèle globaux ?",
Confirm:
"Les paramètres personnalisés de cette discussion seront automatiquement remplacés. Confirmer l'activation des paramètres globaux ?",
Title: "Utiliser la configuration globale",
SubTitle: "Utiliser la configuration globale dans cette conversation",
Confirm: "Voulez-vous definir votre configuration personnalisée ?",
},
HideContext: {
Title: "Masquer les discussions prédéfinies",
SubTitle:
"Les discussions prédéfinies ne seront pas affichées dans l'interface de discussion après masquage",
Title: "Masquer les invites contextuelles",
SubTitle: "Ne pas afficher les instructions contextuelles dans le chat",
},
Share: {
Title: "Partager ce masque",
SubTitle: "Générer un lien direct pour ce masque",
SubTitle: "Générer un lien vers ce masque",
Action: "Copier le lien",
},
},
},
NewChat: {
Return: "Retour",
Skip: "Commencer directement",
NotShow: "Ne plus afficher",
Skip: "Passer",
Title: "Choisir un assitant",
SubTitle: "Discutez avec l'âme derrière le masque",
More: "En savoir plus",
NotShow: "Ne pas afficher à nouveau",
ConfirmNoShow:
"Confirmer la désactivation ? Vous pourrez réactiver cette option à tout moment dans les paramètres.",
Title: "Choisir un masque",
SubTitle: "Commencez maintenant, rencontrez les pensées derrière le masque",
More: "Voir tout",
},
URLCommand: {
Code: "Code d'accès détecté dans le lien, souhaitez-vous le remplir automatiquement ?",
Settings:
"Paramètres prédéfinis détectés dans le lien, souhaitez-vous les remplir automatiquement ?",
"Confirmez-vous vouloir désactiver cela? Vous pouvez le réactiver plus tard dans les paramètres.",
},
UI: {
@@ -561,17 +296,9 @@ const fr: PartialLocaleType = {
Cancel: "Annuler",
Close: "Fermer",
Create: "Créer",
Edit: "Modifier",
Export: "Exporter",
Import: "Importer",
Sync: "Synchroniser",
Config: "Configurer",
Edit: "Éditer",
},
Exporter: {
Description: {
Title:
"Seuls les messages après avoir effacé le contexte seront affichés",
},
Model: "Modèle",
Messages: "Messages",
Topic: "Sujet",

View File

@@ -1,261 +1,228 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
import { PartialLocaleType } from "./index";
const id: PartialLocaleType = {
WIP: "Coming Soon...",
Error: {
Unauthorized: isApp
? "API Key tidak valid terdeteksi, silakan periksa apakah API Key telah dikonfigurasi dengan benar di halaman [Pengaturan](/#/settings)."
: "Kata sandi akses tidak benar atau kosong, silakan masukkan kata sandi akses yang benar di halaman [Masuk](/#/auth), atau masukkan OpenAI API Key Anda di halaman [Pengaturan](/#/settings).",
Unauthorized:
"Akses tidak diizinkan, silakan masukkan kode akses atau masukkan kunci API OpenAI Anda. di halaman [autentikasi](/#/auth) atau di halaman [Pengaturan](/#/settings).",
},
Auth: {
Title: "Kebutuhan Kata Sandi",
Tips: "Administrator telah mengaktifkan verifikasi kata sandi, silakan masukkan kode akses di bawah ini",
SubTips: "Atau masukkan kunci API OpenAI atau Google Anda",
Input: "Masukkan kode akses di sini",
Title: "Diperlukan Kode Akses",
Tips: "Masukkan kode akses di bawah",
SubTips: "Atau masukkan kunci API OpenAI Anda",
Input: "Kode Akses",
Confirm: "Konfirmasi",
Later: "Nanti",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} percakapan`,
ChatItemCount: (count: number) => `${count} pesan`,
},
Chat: {
SubTitle: (count: number) => `Total ${count} percakapan`,
EditMessage: {
Title: "Edit Riwayat Pesan",
Topic: {
Title: "Topik Obrolan",
SubTitle: "Ubah topik obrolan saat ini",
},
},
SubTitle: (count: number) => `${count} pesan`,
Actions: {
ChatList: "Lihat daftar pesan",
CompressedHistory: "Lihat riwayat Prompt yang dikompresi",
Export: "Ekspor riwayat obrolan",
ChatList: "Buka Daftar Chat",
CompressedHistory: "Ekspor Riwayat Terkompresi",
Export: "Ekspor Semua Pesan sebagai Markdown",
Copy: "Salin",
Stop: "Berhenti",
Retry: "Coba lagi",
Pin: "Sematkan",
PinToastContent: "1 percakapan telah disematkan ke prompt default",
Retry: "Coba Lagi",
Pin: "Pin",
PinToastContent: "2 pesan telah ditandai",
PinToastAction: "Lihat",
Delete: "Hapus",
Edit: "Edit",
},
Commands: {
new: "Obrolan Baru",
newm: "Buat Obrolan Baru dari Masker",
next: "Obrolan Berikutnya",
prev: "Obrolan Sebelumnya",
clear: "Hapus Konteks",
del: "Hapus Obrolan",
new: "Mulai Chat Baru",
newm: "Mulai Chat Baru dengan Masks",
next: "Chat Selanjutnya",
prev: "Chat Sebelumnya",
clear: "Bersihkan Percakapan",
del: "Hapus Chat",
},
InputActions: {
Stop: "Hentikan Respons",
ToBottom: "Gulir ke bawah",
Stop: "Berhenti",
ToBottom: "Ke Bagian Bawah",
Theme: {
auto: "Tema Otomatis",
light: "Mode Terang",
dark: "Mode Gelap",
auto: "Otomatis",
light: "Tema Terang",
dark: "Tema Gelap",
},
Prompt: "Perintah Cepat",
Masks: "Semua Masker",
Clear: "Hapus Obrolan",
Settings: "Pengaturan Obrolan",
UploadImage: "Unggah Gambar",
Prompt: "Prompts",
Masks: "Masks",
Clear: "Bersihkan Percakapan",
Settings: "Pengaturan",
},
Rename: "Ganti Nama Obrolan",
Typing: "Sedang Mengetik",
Rename: "Ubah Nama Chat",
Typing: "Mengetik...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} kirim`;
var inputHints = `${submitKey} untuk mengirim`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter untuk baris baru";
inputHints += ", Shift + Enter untuk membalut";
}
return inputHints + "/ untuk melengkapi, : untuk memicu perintah";
return (
inputHints + ", / untuk mencari prompt, : untuk menggunakan perintah"
);
},
Send: "Kirim",
Config: {
Reset: "Hapus Memori",
SaveAs: "Simpan sebagai Masker",
Reset: "Reset ke Default",
SaveAs: "Simpan sebagai Masks",
},
IsContext: "Prompt Default",
},
Export: {
Title: "Bagikan Riwayat Obrolan",
Title: "Ekspor Pesan",
Copy: "Salin Semua",
Download: "Unduh File",
Download: "Unduh",
MessageFromYou: "Pesan dari Anda",
MessageFromChatGPT: "Pesan dari ChatGPT",
Share: "Bagikan ke ShareGPT",
MessageFromYou: "Pengguna",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Format Ekspor",
SubTitle: "Dapat mengekspor teks Markdown atau gambar PNG",
SubTitle: "Markdown atau Gambar PNG",
},
IncludeContext: {
Title: "Sertakan Konteks Masker",
SubTitle: "Apakah akan menampilkan konteks masker dalam pesan",
Title: "Sertakan Konteks",
SubTitle: "Apakah akan menyertakan masks",
},
Steps: {
Select: "Pilih",
Preview: "Prabaca",
},
Image: {
Toast: "Sedang Membuat Screenshot",
Modal: "Tekan lama atau klik kanan untuk menyimpan gambar",
Preview: "Pratinjau",
},
},
Select: {
Search: "Cari Pesan",
Search: "Cari",
All: "Pilih Semua",
Latest: "Beberapa Terbaru",
Clear: "Hapus Pilihan",
Latest: "Pilih Terbaru",
Clear: "Bersihkan",
},
Memory: {
Title: "Ringkasan Sejarah",
EmptyContent: "Isi percakapan terlalu pendek, tidak perlu dirangkum",
Send: "Otomatis kompres riwayat obrolan dan kirim sebagai konteks",
Copy: "Salin Ringkasan",
Reset: "[unused]",
ResetConfirm: "Konfirmasi untuk menghapus ringkasan sejarah?",
Title: "Prompt Memori",
EmptyContent: "Belum ada yang tersedia.",
Send: "Kirim Memori",
Copy: "Salin Memori",
Reset: "Reset",
ResetConfirm:
"Jika Anda mereset, riwayat obrolan saat ini dan memori historis akan dihapus. Apakah Anda yakin ingin melakukan reset?",
},
Home: {
NewChat: "Obrolan Baru",
DeleteChat: "Konfirmasi untuk menghapus percakapan yang dipilih?",
DeleteChat: "Anda yakin ingin menghapus percakapan yang dipilih?",
DeleteToast: "Percakapan telah dihapus",
Revert: "Batalkan",
Revert: "Kembali",
},
Settings: {
Title: "Pengaturan",
SubTitle: "Semua opsi pengaturan",
SubTitle: "Semua Pengaturan",
Danger: {
Reset: {
Title: "Atur Ulang Semua Pengaturan",
SubTitle: "Atur ulang semua opsi pengaturan ke nilai default",
Action: "Atur Ulang Sekarang",
Confirm: "Konfirmasi untuk mengatur ulang semua pengaturan?",
Title: "Setel Ulang Semua Pengaturan",
SubTitle: "Mengembalikan semua pengaturan ke nilai default",
Action: "Setel Ulang",
Confirm:
"Anda yakin ingin mengembalikan semua pengaturan ke nilai default?",
},
Clear: {
Title: "Hapus Semua Data",
SubTitle: "Hapus semua data obrolan dan pengaturan",
Action: "Hapus Sekarang",
SubTitle: "Semua data yang tersimpan secara lokal akan dihapus",
Action: "Hapus",
Confirm:
"Konfirmasi untuk menghapus semua data obrolan dan pengaturan?",
"Apakah Anda yakin ingin menghapus semua data yang tersimpan secara lokal?",
},
},
Lang: {
Name: "Language", // PERHATIAN: jika Anda ingin menambahkan terjemahan baru, harap jangan terjemahkan nilai ini, biarkan sebagai `Language`
Name: "Bahasa", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Semua Bahasa",
},
Avatar: "Avatar",
FontSize: {
Title: "Ukuran Font",
SubTitle: "Ukuran font untuk konten obrolan",
},
FontFamily: {
Title: "Font Obrolan",
SubTitle:
"Font dari konten obrolan, biarkan kosong untuk menerapkan font default global",
Placeholder: "Nama Font",
SubTitle: "Ubah ukuran font konten chat",
},
InjectSystemPrompts: {
Title: "Suntikkan Pesan Sistem",
Title: "Suntikkan Petunjuk Sistem",
SubTitle:
"Memaksa menambahkan pesan sistem simulasi ChatGPT di awal daftar pesan setiap permintaan",
"Tambahkan petunjuk simulasi sistem ChatGPT di awal daftar pesan yang diminta dalam setiap permintaan",
},
InputTemplate: {
Title: "Pra-pemrosesan Input Pengguna",
SubTitle: "Pesan terbaru pengguna akan diisi ke template ini",
Title: "Template Input",
SubTitle: "Pesan baru akan diisi menggunakan template ini",
},
Update: {
Version: (x: string) => `Versi Saat Ini: ${x}`,
IsLatest: "Sudah versi terbaru",
Version: (x: string) => `Version: ${x}`,
IsLatest: "Versi terbaru",
CheckUpdate: "Periksa Pembaruan",
IsChecking: "Sedang memeriksa pembaruan...",
FoundUpdate: (x: string) => `Versi Baru Ditemukan: ${x}`,
GoToUpdate: "Pergi ke Pembaruan",
},
SendKey: "Kunci Kirim",
Theme: "Tema",
TightBorder: "Mode Tanpa Border",
SendPreviewBubble: {
Title: "Preview Bubble",
SubTitle: "Pratinjau konten Markdown di bubble pratinjau",
IsChecking: "Memeriksa pembaruan...",
FoundUpdate: (x: string) => `Versi terbaru ditemukan: ${x}`,
GoToUpdate: "Perbarui Sekarang",
},
AutoGenerateTitle: {
Title: "Otomatis Membuat Judul",
SubTitle: "Membuat judul yang sesuai berdasarkan konten obrolan",
Title: "Hasilkan Judul Otomatis",
SubTitle: "Hasilkan judul yang sesuai berdasarkan konten percakapan",
},
Sync: {
CloudState: "Data Cloud",
CloudState: "Pembaruan Terakhir",
NotSyncYet: "Belum disinkronkan",
Success: "Sinkronisasi Berhasil",
Fail: "Sinkronisasi Gagal",
Config: {
Modal: {
Title: "Konfigurasi Sinkronisasi Cloud",
Check: "Periksa Ketersediaan",
Title: "Konfigurasi Sinkronisasi",
},
SyncType: {
Title: "Jenis Sinkronisasi",
SubTitle: "Pilih server sinkronisasi favorit",
Title: "Tipe Sinkronisasi",
SubTitle: "Pilih layanan sinkronisasi favorit Anda",
},
Proxy: {
Title: "Aktifkan Proxy",
Title: "Aktifkan Proxy CORS",
SubTitle:
"Saat menyinkronkan di browser, proxy harus diaktifkan untuk menghindari pembatasan lintas domain",
"Aktifkan Proxy untuk menghindari pembatasan atau pemblokiran lintas sumber",
},
ProxyUrl: {
Title: "Alamat Proxy",
SubTitle: "Hanya berlaku untuk proxy lintas domain bawaan proyek ini",
Title: "Lokasi Titik Akhir Proxy CORS",
SubTitle: "Hanya berlaku untuk Proxy CORS bawaan untuk proyek ini",
},
WebDav: {
Endpoint: "Alamat WebDAV",
UserName: "Nama Pengguna",
Endpoint: "Lokasi Titik Akhir WebDAV",
UserName: "User Pengguna",
Password: "Kata Sandi",
},
UpStash: {
Endpoint: "Url REST Redis UpStash",
UserName: "Nama Cadangan",
Password: "Token REST Redis UpStash",
},
},
LocalState: "Data Lokal",
Overview: (overview: any) => {
return `${overview.chat} percakapan, ${overview.message} pesan, ${overview.prompt} prompt, ${overview.mask} masker`;
},
ImportFailed: "Impor Gagal",
},
SendKey: "Kirim",
Theme: "Tema",
TightBorder: "Batas Ketat",
SendPreviewBubble: {
Title: "Pratinjau Obrolan",
SubTitle: "Pratinjau Obrolan dengan markdown",
},
Mask: {
Splash: {
Title: "Halaman Awal Masker",
SubTitle: "Tampilkan halaman awal masker saat memulai obrolan baru",
Title: "Layar Pembuka Masks",
SubTitle:
"Tampilkan layar pembuka masks sebelum memulai percakapan baru",
},
Builtin: {
Title: "Sembunyikan Masker Bawaan",
SubTitle: "Sembunyikan masker bawaan dari semua daftar masker",
Title: "Sembunyikan Masks Bawaan",
SubTitle: "Sembunyikan Masks bawaan dari daftar masks",
},
},
Prompt: {
Disable: {
Title: "Nonaktifkan Pelengkapan Prompt Otomatis",
SubTitle:
"Ketik / di awal kotak input untuk memicu pelengkapan otomatis",
Title: "Nonaktifkan Otomatisasi",
SubTitle: "Aktifkan/Matikan otomatisasi",
},
List: "Daftar Prompt Kustom",
List: "Daftar Prompt",
ListCount: (builtin: number, custom: number) =>
`Bawaan ${builtin} item, pengguna ${custom} item`,
`${builtin} bawaan, ${custom} penggunaan khusus`,
Edit: "Edit",
Modal: {
Title: "Daftar Prompt",
Add: "Baru",
Add: "Tambahkan",
Search: "Cari Prompt",
},
EditModal: {
@@ -263,308 +230,155 @@ const id: PartialLocaleType = {
},
},
HistoryCount: {
Title: "Jumlah Pesan Sejarah",
SubTitle: "Jumlah pesan sejarah yang dibawa setiap permintaan",
Title: "Jumlah Pesan Riwayat",
SubTitle: "Jumlah pesan yang akan dikirim setiap permintaan",
},
CompressThreshold: {
Title: "Ambang Batas Kompresi Pesan Sejarah",
Title: "Batas Kompresi Riwayat",
SubTitle:
"Ketika pesan sejarah yang tidak terkompresi melebihi nilai ini, akan dikompresi",
"Jika panjang pesan melebihi batas yang ditentukan, pesan tersebut akan dikompresi",
},
Usage: {
Title: "Cek Saldo",
Title: "Saldo Akun",
SubTitle(used: any, total: any) {
return `Digunakan bulan ini $${used}, total langganan $${total}`;
},
IsChecking: "Sedang memeriksa…",
Check: "Periksa Lagi",
NoAccess: "Masukkan API Key atau kata sandi akses untuk melihat saldo",
},
Access: {
AccessCode: {
Title: "Kata Sandi Akses",
SubTitle: "Administrator telah mengaktifkan akses terenkripsi",
Placeholder: "Masukkan kata sandi akses",
},
CustomEndpoint: {
Title: "Antarmuka Kustom",
SubTitle: "Apakah akan menggunakan layanan Azure atau OpenAI kustom",
},
Provider: {
Title: "Penyedia Layanan Model",
SubTitle: "Ganti penyedia layanan yang berbeda",
},
OpenAI: {
ApiKey: {
Title: "API Key",
SubTitle:
"Gunakan OpenAI Key kustom untuk menghindari batasan akses kata sandi",
Placeholder: "OpenAI API Key",
},
Endpoint: {
Title: "Alamat Antarmuka",
SubTitle: "Selain alamat default, harus menyertakan http(s)://",
},
},
Azure: {
ApiKey: {
Title: "Kunci Antarmuka",
SubTitle:
"Gunakan Azure Key kustom untuk menghindari batasan akses kata sandi",
Placeholder: "Azure API Key",
},
Endpoint: {
Title: "Alamat Antarmuka",
SubTitle: "Contoh:",
},
ApiVerion: {
Title: "Versi Antarmuka (azure api version)",
SubTitle: "Pilih versi parsial tertentu",
},
},
Anthropic: {
ApiKey: {
Title: "Kunci Antarmuka",
SubTitle:
"Gunakan Anthropic Key kustom untuk menghindari batasan akses kata sandi",
Placeholder: "Anthropic API Key",
},
Endpoint: {
Title: "Alamat Antarmuka",
SubTitle: "Contoh:",
},
ApiVerion: {
Title: "Versi Antarmuka (claude api version)",
SubTitle: "Pilih versi API tertentu",
},
},
Google: {
ApiKey: {
Title: "Kunci API",
SubTitle: "Dapatkan kunci API Anda dari Google AI",
Placeholder: "Masukkan kunci API Studio Google AI Anda",
},
Endpoint: {
Title: "Alamat Akhir",
SubTitle: "Contoh:",
},
ApiVersion: {
Title: "Versi API (hanya untuk gemini-pro)",
SubTitle: "Pilih versi API tertentu",
},
GoogleSafetySettings: {
Title: "Tingkat Filter Keamanan Google",
SubTitle: "Atur tingkat filter konten",
},
},
Baidu: {
ApiKey: {
Title: "API Key",
SubTitle: "Gunakan Baidu API Key kustom",
Placeholder: "Baidu API Key",
},
SecretKey: {
Title: "Secret Key",
SubTitle: "Gunakan Baidu Secret Key kustom",
Placeholder: "Baidu Secret Key",
},
Endpoint: {
Title: "Alamat Antarmuka",
SubTitle: "Tidak mendukung kustom, pergi ke .env untuk konfigurasi",
},
},
ByteDance: {
ApiKey: {
Title: "Kunci Antarmuka",
SubTitle: "Gunakan ByteDance API Key kustom",
Placeholder: "ByteDance API Key",
},
Endpoint: {
Title: "Alamat Antarmuka",
SubTitle: "Contoh:",
},
},
Alibaba: {
ApiKey: {
Title: "Kunci Antarmuka",
SubTitle: "Gunakan Alibaba Cloud API Key kustom",
Placeholder: "Alibaba Cloud API Key",
},
Endpoint: {
Title: "Alamat Antarmuka",
SubTitle: "Contoh:",
},
},
CustomModel: {
Title: "Nama Model Kustom",
SubTitle: "Tambahkan opsi model kustom, pisahkan dengan koma",
return `Digunakan bulan ini: ${used}, total langganan: ${total}`;
},
IsChecking: "Memeriksa...",
Check: "Periksa",
NoAccess: "Masukkan kunci API untuk memeriksa saldo",
},
Model: "Model",
Temperature: {
Title: "Randomness (temperature)",
SubTitle: "Semakin tinggi nilainya, semakin acak responsnya",
Title: "Suhu",
SubTitle: "Semakin tinggi nilainya, semakin acak keluarannya",
},
TopP: {
Title: "Sampling Inti (top_p)",
SubTitle:
"Mirip dengan randomness, tetapi jangan ubah bersama randomness",
Title: "Top P",
SubTitle: "Tidak mengubah nilai dengan suhu",
},
MaxTokens: {
Title: "Batas Token Per Respons",
SubTitle: "Jumlah token maksimum yang digunakan per interaksi",
Title: "Token Maksimum",
SubTitle: "Panjang maksimum token input dan output",
},
PresencePenalty: {
Title: "Kedekatan Topik (presence_penalty)",
SubTitle:
"Semakin tinggi nilainya, semakin besar kemungkinan memperluas ke topik baru",
Title: "Penalti Kehadiran",
SubTitle: "Semakin tinggi nilai, semakin mungkin topik baru muncul",
},
FrequencyPenalty: {
Title: "Hukuman Frekuensi (frequency_penalty)",
Title: "Penalti Frekuensi",
SubTitle:
"Semakin tinggi nilainya, semakin besar kemungkinan mengurangi kata-kata yang berulang",
"Semakin tinggi nilai, semakin rendah kemungkinan penggunaan ulang baris yang sama",
},
},
Store: {
DefaultTopic: "Obrolan Baru",
BotHello: "Ada yang bisa saya bantu?",
Error: "Terjadi kesalahan, coba lagi nanti",
DefaultTopic: "Percakapan Baru",
BotHello: "Halo! Bagaimana saya bisa membantu Anda hari ini?",
Error: "Terjadi kesalahan, silakan coba lagi nanti.",
Prompt: {
History: (content: string) =>
"Ini adalah ringkasan obrolan sebelumnya sebagai latar belakang: " +
content,
"Ini adalah ringkasan singkat dari riwayat percakapan: " + content,
Topic:
"Gunakan empat hingga lima kata untuk langsung memberikan ringkasan topik kalimat ini, tanpa penjelasan, tanpa tanda baca, tanpa kata pengisi, tanpa teks tambahan, tanpa menebalkan. Jika tidak ada topik, langsung jawab 'Obrolan Santai'",
"Buat judul berisi empat hingga lima kata untuk percakapan kita yang tidak akan disertakan dalam ringkasan percakapan, seperti instruksi, format, kutipan, tanda baca awal, tanda kutip pendahuluan, atau karakter tambahan. Silakan coba dengan kutipan berakhir.",
Summarize:
"Berikan ringkasan singkat tentang konten obrolan, untuk digunakan sebagai prompt konteks selanjutnya, dalam 200 kata atau kurang",
"Buat ringkasan percakapan dalam 200 kata yang akan digunakan sebagai promp di masa depan.",
},
},
Copy: {
Success: "Telah disalin ke clipboard",
Failed: "Gagal menyalin, mohon berikan izin clipboard",
Success: "Tersalin ke clipboard",
Failed:
"Gagal menyalin, mohon berikan izin untuk mengakses clipboard atau Clipboard API tidak didukung (Tauri)",
},
Download: {
Success: "Konten telah diunduh ke direktori Anda.",
Success: "Konten berhasil diunduh ke direktori Anda.",
Failed: "Unduhan gagal.",
},
Context: {
Toast: (x: any) => `Berisi ${x} prompt preset`,
Toast: (x: any) => `Dengan ${x} promp kontekstual`,
Edit: "Pengaturan Obrolan Saat Ini",
Add: "Tambah Obrolan",
Clear: "Konteks telah dihapus",
Revert: "Kembalikan Konteks",
Add: "Tambahkan Promp",
Clear: "Bersihkan Konteks",
Revert: "Kembali ke Posisi Sebelumnya",
},
Plugin: {
Name: "Plugin",
},
FineTuned: {
Sysmessage: "Anda adalah seorang asisten",
},
SearchChat: {
Name: "Cari",
Page: {
Title: "Cari riwayat obrolan",
Search: "Masukkan kata kunci pencarian",
NoResult: "Tidak ada hasil ditemukan",
NoData: "Tidak ada data",
Loading: "Memuat",
SubTitle: (count: number) => `Ditemukan ${count} hasil`,
},
Item: {
View: "Lihat",
},
Sysmessage: "Anda adalah asisten yang",
},
Mask: {
Name: "Masker",
Name: "Masks",
Page: {
Title: "Preset Karakter Masker",
SubTitle: (count: number) => `${count} definisi karakter preset`,
Search: "Cari Masker Karakter",
Create: "Buat Baru",
Title: "Template Promp",
SubTitle: (count: number) => `${count} template prompt`,
Search: "Cari template",
Create: "Buat",
},
Item: {
Info: (count: number) => `Berisi ${count} obrolan preset`,
Info: (count: number) => `${count} prompt`,
Chat: "Obrolan",
View: "Lihat",
Edit: "Edit",
Delete: "Hapus",
DeleteConfirm: "Konfirmasi penghapusan?",
DeleteConfirm: "Anda yakin ingin menghapus?",
},
EditModal: {
Title: (readonly: boolean) =>
`Edit Masker Preset ${readonly ? "(Hanya Baca)" : ""}`,
Download: "Unduh Preset",
Clone: "Klon Preset",
`Edit Template Prompt ${readonly ? "(hanya baca)" : ""}`,
Download: "Unduh",
Clone: "Duplikat",
},
Config: {
Avatar: "Avatar Karakter",
Name: "Nama Karakter",
Avatar: "Avatar Bot",
Name: "Nama Bot",
Sync: {
Title: "Gunakan Pengaturan Global",
SubTitle:
"Apakah obrolan saat ini akan menggunakan pengaturan model global?",
Title: "Gunakan Konfigurasi Global",
SubTitle: "Gunakan konfigurasi global dalam percakapan ini",
Confirm:
"Pengaturan kustom obrolan saat ini akan ditimpa secara otomatis, konfirmasi untuk mengaktifkan pengaturan global?",
"Pastikan untuk mengganti konfigurasi kustom dengan konfigurasi global?",
},
HideContext: {
Title: "Sembunyikan Obrolan Preset",
SubTitle:
"Setelah disembunyikan, obrolan preset tidak akan muncul di antarmuka obrolan",
Title: "Sembunyikan Prompt Konteks",
SubTitle: "Tidak menampilkan prompt konteks dalam obrolan",
},
Share: {
Title: "Bagikan Masker Ini",
SubTitle: "Hasilkan tautan langsung ke masker ini",
Title: "Bagikan Masks Ini",
SubTitle: "Buat tautan untuk masks ini",
Action: "Salin Tautan",
},
},
},
NewChat: {
Return: "Kembali",
Skip: "Mulai Sekarang",
NotShow: "Jangan Tampilkan Lagi",
Skip: "Lewati",
Title: "Pilih Masks",
SubTitle: "Berkonversasilah dengan diri Anda di balik masks",
More: "Lebih Lanjut",
NotShow: "Jangan Tampilkan Sekarang",
ConfirmNoShow:
"Konfirmasi untuk menonaktifkan? Setelah dinonaktifkan, Anda dapat mengaktifkannya kembali kapan saja di pengaturan.",
Title: "Pilih Masker",
SubTitle: "Mulai sekarang, berinteraksi dengan pemikiran di balik masker",
More: "Lihat Semua",
},
URLCommand: {
Code: "Terdeteksi bahwa tautan sudah mengandung kode akses, apakah akan diisi secara otomatis?",
Settings:
"Terdeteksi bahwa tautan mengandung pengaturan preset, apakah akan diisi secara otomatis?",
"Pastikan untuk menonaktifkannya? Anda dapat mengaktifkannya nanti melalui pengaturan.",
},
UI: {
Confirm: "Konfirmasi",
Cancel: "Batal",
Close: "Tutup",
Create: "Buat Baru",
Create: "Buat",
Edit: "Edit",
Export: "Ekspor",
Import: "Impor",
Sync: "Sinkronkan",
Config: "Konfigurasi",
},
Exporter: {
Description: {
Title: "Hanya pesan setelah menghapus konteks yang akan ditampilkan",
},
Title: "Hanya pesan setelah menghapus konteks yang akan ditampilkan"
},
Model: "Model",
Messages: "Pesan",
Topic: "Topik",
Time: "Waktu",
Time: "Tanggal & Waktu",
},
URLCommand: {
Code: "Kode akses terdeteksi dari url, konfirmasi untuk mendaftar ? ",
Settings: "Pengaturan terdeteksi dari url, konfirmasi untuk diterapkan ?",
},
};

View File

@@ -18,13 +18,10 @@ import ar from "./ar";
import bn from "./bn";
import sk from "./sk";
import { merge } from "../utils/merge";
import { safeLocalStorage } from "@/app/utils";
import type { LocaleType } from "./cn";
export type { LocaleType, PartialLocaleType } from "./cn";
const localStorage = safeLocalStorage();
const ALL_LANGS = {
cn,
en,
@@ -85,26 +82,22 @@ merge(fallbackLang, targetLang);
export default fallbackLang as LocaleType;
function getItem(key: string) {
return localStorage.getItem(key);
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function setItem(key: string, value: string) {
localStorage.setItem(key, value);
try {
localStorage.setItem(key, value);
} catch {}
}
function getLanguage() {
try {
const locale = new Intl.Locale(navigator.language).maximize();
const region = locale?.region?.toLowerCase();
// 1. check region code in ALL_LANGS
if (AllLangs.includes(region as Lang)) {
return region as Lang;
}
// 2. check language code in ALL_LANGS
if (AllLangs.includes(locale.language as Lang)) {
return locale.language as Lang;
}
return DEFAULT_LANG;
return navigator.language.toLowerCase();
} catch {
return DEFAULT_LANG;
}
@@ -117,7 +110,15 @@ export function getLang(): Lang {
return savedLang as Lang;
}
return getLanguage();
const lang = getLanguage();
for (const option of AllLangs) {
if (lang.includes(option)) {
return option;
}
}
return DEFAULT_LANG;
}
export function changeLang(lang: Lang) {

View File

@@ -1,581 +1,238 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const it: PartialLocaleType = {
WIP: "Work in progress...",
Error: {
Unauthorized: isApp
? "API Key non valido rilevato. Vai alla pagina [Impostazioni](/#/settings) per controllare se l'API Key è configurata correttamente."
: "La password di accesso è errata o mancante. Vai alla pagina [Login](/#/auth) per inserire la password corretta o inserisci la tua API Key OpenAI nella pagina [Impostazioni](/#/settings).",
},
Auth: {
Title: "Password richiesta",
Tips: "L'amministratore ha abilitato la verifica della password. Inserisci il codice di accesso qui sotto",
SubTips: "O inserisci la tua chiave API OpenAI o Google",
Input: "Inserisci il codice di accesso qui",
Confirm: "Conferma",
Later: "Più tardi",
Unauthorized:
"Accesso non autorizzato, inserire il codice di accesso nella [pagina](/#/auth) delle impostazioni.",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} conversazioni`,
ChatItemCount: (count: number) => `${count} messaggi`,
},
Chat: {
SubTitle: (count: number) => `Totale ${count} conversazioni`,
EditMessage: {
Title: "Modifica cronologia messaggi",
Topic: {
Title: "Argomento della chat",
SubTitle: "Modifica l'argomento della chat corrente",
},
},
SubTitle: (count: number) => `${count} messaggi con ChatGPT`,
Actions: {
ChatList: "Visualizza l'elenco dei messaggi",
CompressedHistory: "Visualizza la cronologia Prompt compressa",
Export: "Esporta la cronologia chat",
ChatList: "Vai alla Chat List",
CompressedHistory: "Prompt di memoria della cronologia compressa",
Export: "Esportazione di tutti i messaggi come Markdown",
Copy: "Copia",
Stop: "Interrompi",
Stop: "Stop",
Retry: "Riprova",
Pin: "Fissa",
PinToastContent: "1 conversazione fissata ai suggerimenti predefiniti",
PinToastAction: "Visualizza",
Delete: "Elimina",
Edit: "Modifica",
Delete: "Delete",
},
Commands: {
new: "Nuova chat",
newm: "Nuova chat da maschera",
next: "Chat successiva",
prev: "Chat precedente",
clear: "Pulisci contesto",
del: "Elimina chat",
},
InputActions: {
Stop: "Interrompi risposta",
ToBottom: "Scorri fino al più recente",
Theme: {
auto: "Tema automatico",
light: "Tema chiaro",
dark: "Tema scuro",
},
Prompt: "Comandi rapidi",
Masks: "Tutte le maschere",
Clear: "Pulisci chat",
Settings: "Impostazioni conversazione",
UploadImage: "Carica immagine",
},
Rename: "Rinomina conversazione",
Typing: "Digitazione in corso…",
Rename: "Rinomina Chat",
Typing: "Typing…",
Input: (submitKey: string) => {
var inputHints = `${submitKey} per inviare`;
var inputHints = `Scrivi qualcosa e premi ${submitKey} per inviare`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter per andare a capo";
inputHints += ", premi Shift + Enter per andare a capo";
}
return (
inputHints +
"/ per attivare il completamento automatico, : per attivare il comando"
);
return inputHints;
},
Send: "Invia",
Config: {
Reset: "Pulisci memoria",
SaveAs: "Salva come maschera",
Reset: "Reset to Default",
SaveAs: "Save as Mask",
},
IsContext: "Suggerimenti predefiniti",
},
Export: {
Title: "Condividi cronologia chat",
Title: "Tutti i messaggi",
Copy: "Copia tutto",
Download: "Scarica file",
Share: "Condividi su ShareGPT",
MessageFromYou: "Utente",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Formato di esportazione",
SubTitle: "Puoi esportare come testo Markdown o immagine PNG",
},
IncludeContext: {
Title: "Includi contesto maschera",
SubTitle: "Mostrare il contesto della maschera nei messaggi",
},
Steps: {
Select: "Seleziona",
Preview: "Anteprima",
},
Image: {
Toast: "Generazione dello screenshot in corso",
Modal:
"Tieni premuto o fai clic con il tasto destro per salvare l'immagine",
},
},
Select: {
Search: "Cerca messaggi",
All: "Seleziona tutto",
Latest: "Ultimi messaggi",
Clear: "Pulisci selezione",
Download: "Scarica",
MessageFromYou: "Messaggio da te",
MessageFromChatGPT: "Messaggio da ChatGPT",
},
Memory: {
Title: "Riassunto storico",
EmptyContent:
"Il contenuto della conversazione è troppo breve, nessun riassunto necessario",
Send: "Comprimi automaticamente la cronologia chat e inviala come contesto",
Copy: "Copia riassunto",
Reset: "[unused]",
ResetConfirm: "Confermi la cancellazione del riassunto storico?",
Title: "Prompt di memoria",
EmptyContent: "Vuoto.",
Copy: "Copia tutto",
Send: "Send Memory",
Reset: "Reset Session",
ResetConfirm:
"Ripristinare cancellerà la conversazione corrente e la cronologia di memoria. Sei sicuro che vuoi riavviare?",
},
Home: {
NewChat: "Nuova chat",
DeleteChat: "Confermi l'eliminazione della conversazione selezionata?",
DeleteToast: "Conversazione eliminata",
Revert: "Annulla",
NewChat: "Nuova Chat",
DeleteChat: "Confermare la cancellazione della conversazione selezionata?",
DeleteToast: "Chat Cancellata",
Revert: "Revert",
},
Settings: {
Title: "Impostazioni",
SubTitle: "Tutte le opzioni di impostazione",
SubTitle: "Tutte le impostazioni",
Danger: {
Reset: {
Title: "Ripristina tutte le impostazioni",
SubTitle: "Ripristina tutte le opzioni ai valori predefiniti",
Action: "Ripristina subito",
Confirm: "Confermi il ripristino di tutte le impostazioni?",
},
Clear: {
Title: "Elimina tutti i dati",
SubTitle: "Elimina tutte le chat e i dati delle impostazioni",
Action: "Elimina subito",
Confirm:
"Confermi l'eliminazione di tutte le chat e dei dati delle impostazioni?",
},
},
Lang: {
Name: "Language", // ATTENZIONE: se vuoi aggiungere una nuova traduzione, non tradurre questo valore, lascialo come `Language`
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Tutte le lingue",
},
Avatar: "Avatar",
FontSize: {
Title: "Dimensione del carattere",
SubTitle: "Dimensione del carattere per il contenuto della chat",
},
FontFamily: {
Title: "Font della Chat",
SubTitle:
"Carattere del contenuto della chat, lascia vuoto per applicare il carattere predefinito globale",
Placeholder: "Nome del Font",
Title: "Dimensione carattere",
SubTitle: "Regolare la dimensione dei caratteri del contenuto della chat",
},
InjectSystemPrompts: {
Title: "Inserisci suggerimenti di sistema",
Title: "Inserisci Prompts di Sistema",
SubTitle:
"Aggiungi forzatamente un suggerimento di sistema simulato di ChatGPT all'inizio della lista dei messaggi per ogni richiesta",
"Aggiungi forzatamente un prompt di sistema simulato di ChatGPT all'inizio della lista dei messaggi per ogni richiesta",
},
InputTemplate: {
Title: "Preprocessing dell'input utente",
SubTitle:
"L'ultimo messaggio dell'utente verrà inserito in questo modello",
},
Update: {
Version: (x: string) => `Versione attuale: ${x}`,
IsLatest: "È l'ultima versione",
Version: (x: string) => `Versione: ${x}`,
IsLatest: "Ultima versione",
CheckUpdate: "Controlla aggiornamenti",
IsChecking: "Verifica aggiornamenti in corso...",
FoundUpdate: (x: string) => `Nuova versione trovata: ${x}`,
GoToUpdate: "Vai all'aggiornamento",
IsChecking: "Sto controllando gli aggiornamenti...",
FoundUpdate: (x: string) => `Trovata nuova versione: ${x}`,
GoToUpdate: "Aggiorna",
},
SendKey: "Tasto di invio",
SendKey: "Tasto invia",
Theme: "Tema",
TightBorder: "Modalità senza bordi",
TightBorder: "Schermo intero",
SendPreviewBubble: {
Title: "Bolla di anteprima",
SubTitle: "Anteprima del contenuto Markdown nella bolla di anteprima",
},
AutoGenerateTitle: {
Title: "Generazione automatica del titolo",
SubTitle:
"Genera un titolo appropriato in base al contenuto della conversazione",
},
Sync: {
CloudState: "Dati cloud",
NotSyncYet: "Non è ancora avvenuta alcuna sincronizzazione",
Success: "Sincronizzazione riuscita",
Fail: "Sincronizzazione fallita",
Config: {
Modal: {
Title: "Configura sincronizzazione cloud",
Check: "Controlla disponibilità",
},
SyncType: {
Title: "Tipo di sincronizzazione",
SubTitle: "Scegli il server di sincronizzazione preferito",
},
Proxy: {
Title: "Abilita proxy",
SubTitle:
"Durante la sincronizzazione nel browser, è necessario abilitare il proxy per evitare restrizioni CORS",
},
ProxyUrl: {
Title: "Indirizzo proxy",
SubTitle: "Solo per il proxy CORS fornito con questo progetto",
},
WebDav: {
Endpoint: "Indirizzo WebDAV",
UserName: "Nome utente",
Password: "Password",
},
UpStash: {
Endpoint: "URL REST di UpStash Redis",
UserName: "Nome di backup",
Password: "Token REST di UpStash Redis",
},
},
LocalState: "Dati locali",
Overview: (overview: any) => {
return `${overview.chat} chat, ${overview.message} messaggi, ${overview.prompt} suggerimenti, ${overview.mask} maschere`;
},
ImportFailed: "Importazione fallita",
Title: "Anteprima di digitazione",
SubTitle: "Preview markdown in bubble",
},
Mask: {
Splash: {
Title: "Pagina di avvio delle maschere",
SubTitle:
"Mostra la pagina di avvio delle maschere quando si avvia una nuova chat",
},
Builtin: {
Title: "Nascondi maschere predefinite",
SubTitle:
"Nascondi le maschere predefinite in tutte le liste delle maschere",
Title: "Mask Splash Screen",
SubTitle: "Show a mask splash screen before starting new chat",
},
},
Prompt: {
Disable: {
Title: "Disabilita completamento automatico dei suggerimenti",
SubTitle:
"Inserisci / all'inizio della casella di input per attivare il completamento automatico",
Title: "Disabilita l'auto completamento",
SubTitle: "Input / per attivare il completamento automatico",
},
List: "Elenco dei suggerimenti personalizzati",
List: "Elenco dei suggerimenti",
ListCount: (builtin: number, custom: number) =>
`${builtin} predefiniti, ${custom} definiti dall'utente`,
`${builtin} built-in, ${custom} user-defined`,
Edit: "Modifica",
Modal: {
Title: "Elenco dei suggerimenti",
Add: "Nuovo",
Search: "Cerca suggerimenti",
Title: "Prompt List",
Add: "Add One",
Search: "Search Prompts",
},
EditModal: {
Title: "Modifica suggerimenti",
Title: "Edit Prompt",
},
},
HistoryCount: {
Title: "Numero di messaggi storici inclusi",
SubTitle: "Numero di messaggi storici inclusi in ogni richiesta",
Title: "Conteggio dei messaggi allegati",
SubTitle: "Numero di messaggi inviati allegati per richiesta",
},
CompressThreshold: {
Title: "Soglia di compressione dei messaggi storici",
Title: "Soglia di compressione della cronologia",
SubTitle:
"Quando i messaggi storici non compressi superano questo valore, verranno compressi",
"Comprimerà se la lunghezza dei messaggi non compressi supera il valore",
},
Usage: {
Title: "Verifica saldo",
Title: "Bilancio Account",
SubTitle(used: any, total: any) {
return `Utilizzato questo mese $${used}, totale abbonamento $${total}`;
return `Attualmente usato in questo mese $${used}, soglia massima $${total}`;
},
IsChecking: "Verifica in corso…",
Check: "Verifica di nuovo",
NoAccess:
"Inserisci API Key o password di accesso per visualizzare il saldo",
IsChecking: "Controllando...",
Check: "Controlla ancora",
NoAccess: "Inserire la chiave API per controllare il saldo",
},
Access: {
AccessCode: {
Title: "Password di accesso",
SubTitle: "L'amministratore ha abilitato l'accesso criptato",
Placeholder: "Inserisci la password di accesso",
},
CustomEndpoint: {
Title: "Interfaccia personalizzata",
SubTitle: "Utilizzare servizi Azure o OpenAI personalizzati",
},
Provider: {
Title: "Fornitore del modello",
SubTitle: "Cambia fornitore di servizi",
},
OpenAI: {
ApiKey: {
Title: "API Key",
SubTitle:
"Utilizza una chiave OpenAI personalizzata per bypassare le limitazioni di accesso",
Placeholder: "API Key OpenAI",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle: "Deve includere http(s):// oltre all'indirizzo predefinito",
},
},
Azure: {
ApiKey: {
Title: "Chiave dell'interfaccia",
SubTitle:
"Utilizza una chiave Azure personalizzata per bypassare le limitazioni di accesso",
Placeholder: "Chiave API Azure",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle: "Esempio:",
},
ApiVerion: {
Title: "Versione dell'interfaccia (versione api azure)",
SubTitle: "Scegli una versione specifica",
},
},
Anthropic: {
ApiKey: {
Title: "Chiave dell'interfaccia",
SubTitle:
"Utilizza una chiave Anthropic personalizzata per bypassare le limitazioni di accesso",
Placeholder: "API Key Anthropic",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle: "Esempio:",
},
ApiVerion: {
Title: "Versione dell'interfaccia (versione api claude)",
SubTitle: "Scegli una versione API specifica",
},
},
Google: {
ApiKey: {
Title: "API Key",
SubTitle: "Ottieni la tua chiave API da Google AI",
Placeholder: "Inserisci la tua chiave API Google AI Studio",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle: "Esempio:",
},
ApiVersion: {
Title: "Versione API (solo per gemini-pro)",
SubTitle: "Scegli una versione API specifica",
},
GoogleSafetySettings: {
Title: "Livello di filtraggio sicurezza Google",
SubTitle: "Imposta il livello di filtraggio dei contenuti",
},
},
Baidu: {
ApiKey: {
Title: "API Key",
SubTitle: "Utilizza una chiave API Baidu personalizzata",
Placeholder: "API Key Baidu",
},
SecretKey: {
Title: "Secret Key",
SubTitle: "Utilizza una chiave segreta Baidu personalizzata",
Placeholder: "Secret Key Baidu",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle:
"Non supporta configurazioni personalizzate, andare su .env",
},
},
ByteDance: {
ApiKey: {
Title: "Chiave dell'interfaccia",
SubTitle: "Utilizza una chiave API ByteDance personalizzata",
Placeholder: "API Key ByteDance",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle: "Esempio:",
},
},
Alibaba: {
ApiKey: {
Title: "Chiave dell'interfaccia",
SubTitle: "Utilizza una chiave API Alibaba Cloud personalizzata",
Placeholder: "API Key Alibaba Cloud",
},
Endpoint: {
Title: "Indirizzo dell'interfaccia",
SubTitle: "Esempio:",
},
},
CustomModel: {
Title: "Nome del modello personalizzato",
SubTitle:
"Aggiungi opzioni di modelli personalizzati, separati da virgole",
},
},
Model: "Modello (model)",
Model: "Modello GPT",
Temperature: {
Title: "Casualità (temperature)",
SubTitle: "Valore più alto, risposte più casuali",
},
TopP: {
Title: "Campionamento nucleare (top_p)",
SubTitle:
"Simile alla casualità, ma non cambiarlo insieme alla casualità",
Title: "Temperature",
SubTitle: "Un valore maggiore rende l'output più casuale",
},
MaxTokens: {
Title: "Limite di token per risposta (max_tokens)",
SubTitle: "Numero massimo di token per ogni interazione",
Title: "Token massimi",
SubTitle: "Lunghezza massima dei token in ingresso e dei token generati",
},
PresencePenalty: {
Title: "Novità del tema (presence_penalty)",
Title: "Penalità di presenza",
SubTitle:
"Valore più alto, maggiore possibilità di espandere a nuovi argomenti",
"Un valore maggiore aumenta la probabilità di parlare di nuovi argomenti",
},
FrequencyPenalty: {
Title: "Penalità di frequenza (frequency_penalty)",
Title: "Penalità di frequenza",
SubTitle:
"Valore più alto, maggiore possibilità di ridurre le ripetizioni",
"Un valore maggiore che diminuisce la probabilità di ripetere la stessa riga",
},
},
Store: {
DefaultTopic: "Nuova chat",
BotHello: "Come posso aiutarti?",
Error: "Si è verificato un errore, riprova più tardi",
DefaultTopic: "Nuova conversazione",
BotHello: "Ciao, come posso aiutarti oggi?",
Error: "Qualcosa è andato storto, riprova più tardi.",
Prompt: {
History: (content: string) =>
"Questo è un riassunto della chat storica come contesto: " + content,
"Questo è un riassunto della cronologia delle chat tra l'IA e l'utente:" +
content,
Topic:
"Riporta il tema di questa frase in modo conciso con quattro o cinque parole, senza spiegazioni, punteggiatura, interiezioni, testo superfluo e senza grassetto. Se non c'è un tema, rispondi direttamente con 'chit-chat'",
"Si prega di generare un titolo di quattro o cinque parole che riassuma la nostra conversazione senza alcuna traccia, punteggiatura, virgolette, punti, simboli o testo aggiuntivo. Rimuovere le virgolette",
Summarize:
"Riassumi brevemente il contenuto della conversazione come prompt di contesto per il seguito, mantenendolo entro 200 parole",
"Riassumi brevemente la nostra discussione in 200 caratteri o meno per usarla come spunto per una futura conversazione.",
},
},
Copy: {
Success: "Copiato negli appunti",
Failed: "Copia fallita, concedi i permessi per gli appunti",
},
Download: {
Success: "Contenuto scaricato nella tua directory.",
Failed: "Download fallito.",
Success: "Copiato sugli appunti",
Failed:
"Copia fallita, concedere l'autorizzazione all'accesso agli appunti",
},
Context: {
Toast: (x: any) => `Include ${x} suggerimenti predefiniti`,
Edit: "Impostazioni della conversazione attuale",
Add: "Aggiungi una conversazione",
Clear: "Contesto cancellato",
Revert: "Ripristina contesto",
Toast: (x: any) => `Con ${x} prompts contestuali`,
Edit: "Prompt contestuali e di memoria",
Add: "Aggiungi altro",
},
Plugin: {
Name: "Plugin",
},
FineTuned: {
Sysmessage: "Sei un assistente",
},
SearchChat: {
Name: "Cerca",
Page: {
Title: "Cerca nei messaggi",
Search: "Inserisci parole chiave per la ricerca",
NoResult: "Nessun risultato trovato",
NoData: "Nessun dato",
Loading: "Caricamento in corso",
SubTitle: (count: number) => `Trovati ${count} risultati`,
},
Item: {
View: "Visualizza",
},
Sysmessage: "Sei un assistente che",
},
Mask: {
Name: "Maschera",
Name: "Mask",
Page: {
Title: "Maschere dei ruoli predefiniti",
SubTitle: (count: number) => `${count} definizioni di ruoli predefiniti`,
Search: "Cerca maschere di ruolo",
Create: "Crea nuovo",
Title: "Prompt Template",
SubTitle: (count: number) => `${count} prompt templates`,
Search: "Search Templates",
Create: "Create",
},
Item: {
Info: (count: number) => `Include ${count} conversazioni predefinite`,
Chat: "Conversazione",
View: "Visualizza",
Edit: "Modifica",
Delete: "Elimina",
DeleteConfirm: "Confermi eliminazione?",
Info: (count: number) => `${count} prompts`,
Chat: "Chat",
View: "View",
Edit: "Edit",
Delete: "Delete",
DeleteConfirm: "Confirm to delete?",
},
EditModal: {
Title: (readonly: boolean) =>
`Modifica maschera predefinita ${readonly ? "(sola lettura)" : ""}`,
Download: "Scarica predefinito",
Clone: "Clona predefinito",
`Edit Prompt Template ${readonly ? "(readonly)" : ""}`,
Download: "Download",
Clone: "Clone",
},
Config: {
Avatar: "Avatar del ruolo",
Name: "Nome del ruolo",
Sync: {
Title: "Utilizza impostazioni globali",
SubTitle:
"La conversazione attuale utilizzerà le impostazioni globali del modello",
Confirm:
"Le impostazioni personalizzate della conversazione attuale verranno sovrascritte automaticamente, confermi l'attivazione delle impostazioni globali?",
},
HideContext: {
Title: "Nascondi conversazioni predefinite",
SubTitle:
"Le conversazioni predefinite non appariranno nella finestra della chat dopo averle nascoste",
},
Share: {
Title: "Condividi questa maschera",
SubTitle: "Genera un link diretto a questa maschera",
Action: "Copia link",
},
Avatar: "Bot Avatar",
Name: "Bot Name",
},
},
NewChat: {
Return: "Torna",
Skip: "Inizia subito",
NotShow: "Non mostrare più",
ConfirmNoShow:
"Confermi di disabilitare? Dopo la disabilitazione, puoi riattivare in qualsiasi momento dalle impostazioni.",
Title: "Scegli una maschera",
SubTitle: "Inizia ora e interagisci con il pensiero dietro la maschera",
More: "Vedi tutto",
},
URLCommand: {
Code: "Codice di accesso rilevato nel link, riempirlo automaticamente?",
Settings:
"Impostazioni predefinite rilevate nel link, riempirle automaticamente?",
Return: "Return",
Skip: "Skip",
Title: "Pick a Mask",
SubTitle: "Chat with the Soul behind the Mask",
More: "Find More",
NotShow: "Not Show Again",
ConfirmNoShow: "Confirm to disableYou can enable it in settings later.",
},
UI: {
Confirm: "Conferma",
Cancel: "Annulla",
Close: "Chiudi",
Create: "Crea",
Edit: "Modifica",
Export: "Esporta",
Import: "Importa",
Sync: "Sincronizza",
Config: "Configura",
Confirm: "Confirm",
Cancel: "Cancel",
Close: "Close",
Create: "Create",
Edit: "Edit",
},
Exporter: {
Description: {
Title:
"Solo i messaggi dopo la cancellazione del contesto verranno visualizzati",
},
Model: "Modello",
Messages: "Messaggi",
Topic: "Tema",
Topic: "Argomento",
Time: "Tempo",
},
};

View File

@@ -1,564 +1,301 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const jp: PartialLocaleType = {
WIP: "この機能は開発中です",
Error: {
Unauthorized: isApp
? "無効なAPIキーが検出されました。[設定](/#/settings)ページでAPIキーが正しく設定されているか確認してください。"
: "アクセスパスワードが正しくないか空です。[ログイン](/#/auth)ページで正しいアクセスパスワードを入力するか、[設定](/#/settings)ページで自分のOpenAI APIキーを入力してください。",
},
Auth: {
Title: "パスワードが必要です",
Tips: "管理者がパスワード認証を有効にしました。以下にアクセスコードを入力してください",
SubTips: "または、OpenAIまたはGoogle APIキーを入力してください",
Input: "ここにアクセスコードを入力",
Confirm: "確認",
Later: "後で",
Unauthorized:
"現在は未承認状態です。左下の設定ボタンをクリックし、アクセスパスワードかOpenAIのAPIキーを入力してください。",
},
ChatItem: {
ChatItemCount: (count: number) => `${count}件の会話`,
ChatItemCount: (count: number) => `${count} 通のチャット`,
},
Chat: {
SubTitle: (count: number) => `合計${count}件の会話`,
SubTitle: (count: number) => `ChatGPTとの ${count} 通のチャット`,
EditMessage: {
Title: "メッセージ履歴を編集",
Title: "全てのメッセージを修正",
Topic: {
Title: "チャットテーマ",
SubTitle: "現在のチャットテーマを変更",
Title: "トピック",
SubTitle: "このトピックを変える",
},
},
Actions: {
ChatList: "メッセージリストを見る",
CompressedHistory: "圧縮された履歴プロンプトを見る",
ChatList: "メッセージリストを表示",
CompressedHistory: "圧縮された履歴プロンプトを表示",
Export: "チャット履歴をエクスポート",
Copy: "コピー",
Stop: "停止",
Retry: "再試行",
Pin: "固定",
PinToastContent: "1件の会話をプリセットプロンプトに固定しました",
PinToastAction: "見る",
Retry: "リトライ",
Pin: "ピン",
PinToastContent:
"コンテキストプロンプトに1つのメッセージをピン留めしました",
PinToastAction: "表示",
Delete: "削除",
Edit: "編集",
},
Commands: {
new: "新しいチャット",
newm: "マスクから新しいチャット",
next: "次のチャット",
prev: "前のチャット",
clear: "コンテキストをクリア",
del: "チャットを削除",
},
InputActions: {
Stop: "応答を停止",
ToBottom: "最新へスクロール",
Theme: {
auto: "自動テーマ",
light: "ライトモード",
dark: "ダークモード",
},
Prompt: "クイックコマンド",
Masks: "すべてのマスク",
Clear: "チャットをクリア",
Settings: "チャット設定",
UploadImage: "画像をアップロード",
},
Rename: "チャットの名前を変更",
Typing: "入力中…",
Input: (submitKey: string) => {
var inputHints = `${submitKey}で送信`;
var inputHints = `${submitKey} で送信`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enterで改行";
inputHints += "Shift + Enter で改行";
}
return inputHints + "、/で補完をトリガー、:でコマンドをトリガー";
return inputHints + "/ で自動補完をトリガー";
},
Send: "送信",
Config: {
Reset: "メモリをクリア",
SaveAs: "マスクとして保存",
Reset: "リセット",
SaveAs: "保存",
},
IsContext: "プリセットプロンプト",
},
Export: {
Title: "チャット履歴を共有",
Title: "チャット履歴をMarkdown形式でエクスポート",
Copy: "すべてコピー",
Download: "ファイルをダウンロード",
Share: "ShareGPTに共有",
MessageFromYou: "ユーザー",
MessageFromChatGPT: "ChatGPT",
MessageFromYou: "あなたからのメッセージ",
MessageFromChatGPT: "ChatGPTからのメッセージ",
Format: {
Title: "エクスポート形式",
SubTitle: "MarkdownテキストまたはPNG画像としてエクスポートできます",
Title: "フォーマットをエクスポート",
SubTitle: "マークダウン形式、PNG画像形式を選択できます",
},
IncludeContext: {
Title: "マスクコンテキストを含",
SubTitle: "メッセージにマスクコンテキストを表示するかどうか",
Title: "コンテキストを含みますか?",
SubTitle: "コンテキストを含ませるか否か",
},
Steps: {
Select: "選択",
Select: "エクスポート設定",
Preview: "プレビュー",
},
Image: {
Toast: "スクリーンショットを生成中",
Modal: "長押しまたは右クリックして画像を保存",
Toast: "画像生成中...",
Modal: "長押しまたは右クリックで保存してください。",
},
},
Select: {
Search: "メッセージを検索",
Search: "検索",
All: "すべて選択",
Latest: "最新の数件",
Clear: "選択をクリア",
Latest: "新しいメッセージを選択",
Clear: "クリア",
},
Memory: {
Title: "履歴の要約",
EmptyContent: "対話内容が短いため、要約は不要です",
Send: "チャット履歴を自動的に圧縮し、コンテキストとして送信",
Copy: "要約をコピー",
Reset: "[unused]",
ResetConfirm: "履歴の要約をリセットしてもよろしいですか?",
Title: "履歴メモリ",
EmptyContent: "まだ記憶されていません",
Send: "メモリを送信",
Copy: "メモリをコピー",
Reset: "チャットをリセット",
ResetConfirm:
"リセット後、現在のチャット履歴と過去のメモリがクリアされます。リセットしてもよろしいですか?",
},
Home: {
NewChat: "新しいチャット",
DeleteChat: "選択した会話を削除してもよろしいですか?",
DeleteToast: "会話を削除しました",
DeleteChat: "選択したチャットを削除してもよろしいですか?",
DeleteToast: "チャットが削除されました",
Revert: "元に戻す",
},
Settings: {
Title: "設定",
SubTitle: "すべての設定オプション",
SubTitle: "設定オプション",
Danger: {
Reset: {
Title: "すべての設定をリセット",
SubTitle: "すべての設定項目をデフォルトにリセット",
Action: "今すぐリセット",
Confirm: "すべての設定をリセットしてもよろしいですか?",
Title: "設定をリセット",
SubTitle: "すべての設定項目をデフォルトにリセットします",
Action: "今すぐリセットする",
Confirm: "すべての設定項目をリセットしてもよろしいですか?",
},
Clear: {
Title: "すべてのデータをクリア",
SubTitle: "すべてのチャット、設定データをクリア",
Action: "今すぐクリア",
Confirm: "すべてのチャット、設定データをクリアしてもよろしいですか?",
Title: "データを消去",
SubTitle: "すべてのチャット履歴と設定を消去します",
Action: "今すぐ消去する",
Confirm: "すべてのチャット履歴と設定を消去しますか?",
},
},
Lang: {
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "すべての言語",
All: "ての言語",
},
Avatar: "アバター",
FontSize: {
Title: "フォントサイズ",
SubTitle: "チャット内容のフォントサイズ",
},
FontFamily: {
Title: "チャットフォント",
SubTitle:
"チャットコンテンツのフォント、空白の場合はグローバルデフォルトフォントを適用します",
Placeholder: "フォント名",
},
InjectSystemPrompts: {
Title: "システムプロンプトの入",
Title: "システムプロンプトの入",
SubTitle:
"すべてのリクエストメッセージリストの先頭にChatGPTのシステムプロンプトを強制的に追加",
"リクエストメッセージリストの先頭にChatGPTのシステムプロンプトを強制的に追加します",
},
InputTemplate: {
Title: "ユーザー入力のプリプロセス",
SubTitle: "最新のメッセージをこのテンプレートに埋め込",
Title: "入力の前処理",
SubTitle: "新規入力がこのテンプレートに埋め込まれます",
},
Update: {
Version: (x: string) => `現在のバージョン:${x}`,
IsLatest: "最新バージョンです",
CheckUpdate: "更新を確認",
IsChecking: "更新を確認中...",
FoundUpdate: (x: string) => `新しいバージョンを発見${x}`,
GoToUpdate: "更新へ進む",
CheckUpdate: "アップデートを確認",
IsChecking: "アップデートを確認しています...",
FoundUpdate: (x: string) => `新しいバージョンが見つかりました${x}`,
GoToUpdate: "更新する",
},
SendKey: "送信キー",
Theme: "テーマ",
TightBorder: "ボーダーレスモード",
SendPreviewBubble: {
Title: "プレビューバブル",
SubTitle: "プレビューバブルでMarkdownコンテンツをプレビュー",
},
AutoGenerateTitle: {
Title: "自動タイトル生成",
SubTitle: "チャット内容に基づいて適切なタイトルを生成",
},
Sync: {
CloudState: "クラウドデータ",
NotSyncYet: "まだ同期されていません",
Success: "同期に成功しました",
Fail: "同期に失敗しました",
Config: {
Modal: {
Title: "クラウド同期の設定",
Check: "可用性を確認",
},
SyncType: {
Title: "同期タイプ",
SubTitle: "好きな同期サーバーを選択",
},
Proxy: {
Title: "プロキシを有効化",
SubTitle:
"ブラウザで同期する場合、クロスオリジン制限を避けるためにプロキシを有効にする必要があります",
},
ProxyUrl: {
Title: "プロキシURL",
SubTitle: "このプロジェクトに組み込まれたクロスオリジンプロキシ専用",
},
WebDav: {
Endpoint: "WebDAV エンドポイント",
UserName: "ユーザー名",
Password: "パスワード",
},
UpStash: {
Endpoint: "UpStash Redis REST URL",
UserName: "バックアップ名",
Password: "UpStash Redis REST トークン",
},
},
LocalState: "ローカルデータ",
Overview: (overview: any) => {
return `${overview.chat} 回の対話、${overview.message} 件のメッセージ、${overview.prompt} 件のプロンプト、${overview.mask} 件のマスク`;
},
ImportFailed: "インポートに失敗しました",
Title: "プレビューバブルの送信",
SubTitle: "プレビューバブルでマークダウンコンテンツをプレビュー",
},
Mask: {
Splash: {
Title: "マスク起動画面",
SubTitle: "新しいチャット作成する際にマスク起動画面を表示",
Title: "キャラクターページ",
SubTitle: "新チャット作成時にキャラクターページを表示する",
},
Builtin: {
Title: "内蔵マスクを非表示",
SubTitle: "すべてのマスクリストで内蔵マスクを非表示",
Title: "ビルトインマスクを非表示",
SubTitle: "マスクリストからビルトインを非表示する",
},
},
Prompt: {
Disable: {
Title: "プロンプトの自動補完を無効",
SubTitle: "入力フィールドの先頭に / を入力して自動補完をトリガー",
Title: "プロンプトの自動補完を無効にする",
SubTitle:
"入力フィールドの先頭に / を入力すると、自動補完がトリガーされます。",
},
List: "カスタムプロンプトリスト",
ListCount: (builtin: number, custom: number) =>
`内蔵 ${builtin} 件、ユーザー定義 ${custom}`,
`組み込み ${builtin} 件、ユーザー定義 ${custom}`,
Edit: "編集",
Modal: {
Title: "プロンプトリスト",
Add: "新規作成",
Search: "プロンプト検索",
Add: "新規追加",
Search: "プロンプトワード検索",
},
EditModal: {
Title: "プロンプトを編集",
Title: "編集",
},
},
HistoryCount: {
Title: "履歴メッセージ数",
SubTitle: "リクエストに含まれる履歴メッセージ数",
Title: "履歴メッセージ数を添付",
SubTitle: "リクエストごとに添付する履歴メッセージ数",
},
CompressThreshold: {
Title: "履歴メッセージの圧縮閾値",
SubTitle: "未圧縮の履歴メッセージがこの値を超えた場合、圧縮が行われます",
Title: "履歴メッセージの長さ圧縮しきい値",
SubTitle:
"圧縮されていない履歴メッセージがこの値を超えた場合、圧縮が行われます。",
},
Usage: {
Title: "残高確認",
Title: "残高照会",
SubTitle(used: any, total: any) {
return `今月の使用量 $${used}、サブスクリプション合計 $${total}`;
return `今月 $${used} を使用しました。総額は $${total} です。`;
},
IsChecking: "確認中",
IsChecking: "確認中...",
Check: "再確認",
NoAccess: "APIキーまたはアクセスパスワードを入力して残高を確認",
NoAccess: "APIキーまたはアクセスパスワードを入力して残高を表示",
},
Access: {
AccessCode: {
Title: "アクセスパスワード",
SubTitle: "管理者が暗号化アクセスを有効にしました",
Placeholder: "アクセスパスワードを入力してください",
},
CustomEndpoint: {
Title: "カスタムエンドポイント",
SubTitle: "カスタムAzureまたはOpenAIサービスを使用するかどうか",
},
Provider: {
Title: "モデルプロバイダー",
SubTitle: "異なるプロバイダーに切り替える",
},
OpenAI: {
ApiKey: {
Title: "APIキー",
SubTitle: "カスタムOpenAIキーを使用してパスワードアクセス制限を回避",
Placeholder: "OpenAI APIキー",
},
Endpoint: {
Title: "エンドポイント",
SubTitle:
"デフォルト以外のアドレスにはhttp(s)://を含める必要があります",
},
},
Azure: {
ApiKey: {
Title: "APIキー",
SubTitle: "カスタムAzureキーを使用してパスワードアクセス制限を回避",
Placeholder: "Azure APIキー",
},
Endpoint: {
Title: "エンドポイント",
SubTitle: "例:",
},
ApiVerion: {
Title: "APIバージョン (azure api version)",
SubTitle: "特定のバージョンを選択",
},
},
Anthropic: {
ApiKey: {
Title: "APIキー",
SubTitle:
"カスタムAnthropicキーを使用してパスワードアクセス制限を回避",
Placeholder: "Anthropic APIキー",
},
Endpoint: {
Title: "エンドポイント",
SubTitle: "例:",
},
ApiVerion: {
Title: "APIバージョン (claude api version)",
SubTitle: "特定のAPIバージョンを選択",
},
},
Google: {
ApiKey: {
Title: "APIキー",
SubTitle: "Google AIからAPIキーを取得",
Placeholder: "Google AI Studio APIキーを入力",
},
Endpoint: {
Title: "エンドポイント",
SubTitle: "例:",
},
ApiVersion: {
Title: "APIバージョンgemini-pro専用",
SubTitle: "特定のAPIバージョンを選択",
},
GoogleSafetySettings: {
Title: "Google セーフティ設定",
SubTitle: "コンテンツフィルタリングレベルを設定",
},
},
Baidu: {
ApiKey: {
Title: "APIキー",
SubTitle: "カスタムBaidu APIキーを使用",
Placeholder: "Baidu APIキー",
},
SecretKey: {
Title: "シークレットキー",
SubTitle: "カスタムBaiduシークレットキーを使用",
Placeholder: "Baiduシークレットキー",
},
Endpoint: {
Title: "エンドポイント",
SubTitle: "カスタムはサポートしていません、.env設定に進んでください",
},
},
ByteDance: {
ApiKey: {
Title: "APIキー",
SubTitle: "カスタムByteDance APIキーを使用",
Placeholder: "ByteDance APIキー",
},
Endpoint: {
Title: "エンドポイント",
SubTitle: "例:",
},
},
Alibaba: {
ApiKey: {
Title: "APIキー",
SubTitle: "カスタムAlibaba Cloud APIキーを使用",
Placeholder: "Alibaba Cloud APIキー",
},
Endpoint: {
Title: "エンドポイント",
SubTitle: "例:",
},
},
CustomModel: {
Title: "カスタムモデル名",
SubTitle: "カスタムモデルの選択肢を追加、英語のカンマで区切る",
},
},
Model: "モデル (model)",
Temperature: {
Title: "ランダム性 (temperature)",
SubTitle: "値が大きいほど応答がランダムになります",
},
TopP: {
Title: "トップP (top_p)",
SubTitle:
"ランダム性に似ていますが、ランダム性と一緒に変更しないでください",
"値が大きいほど、回答がランダムになります。1以上の値には文字化けが含まれる可能性があります。",
},
MaxTokens: {
Title: "1回の応答制限 (max_tokens)",
SubTitle: "1回の対話で使用される最大トークン数",
Title: "シングルレスポンス制限 (max_tokens)",
SubTitle: "1回のインタラクションで使用される最大トークン数",
},
PresencePenalty: {
Title: "新鮮度 (presence_penalty)",
SubTitle: "値が大きいほど新しいトピックに移行する可能性が高くなります",
Title: "トピックの新鮮度 (presence_penalty)",
SubTitle: "値が大きいほど新しいトピックへの展開が可能になります",
},
FrequencyPenalty: {
Title: "頻度ペナルティ (frequency_penalty)",
SubTitle: "値が大きいほど繰り返しの単語が減少します",
Title: "話題の頻度 (frequency_penalty)",
SubTitle: "値が大きいほど、重複語を低減する可能性が高くなります",
},
AutoGenerateTitle: {
Title: "タイトルの自動生成",
SubTitle: "会話内容に基づいて適切なタイトルを生成する",
},
},
Store: {
DefaultTopic: "新しいチャット",
BotHello: "何かお手伝いできますか",
Error: "エラーが発生しました。後でもう一度試してください",
BotHello: "何かお手伝いできることはありますか",
Error: "エラーが発生しました。しばらくしてからやり直してください",
Prompt: {
History: (content: string) =>
"これは前提としての履歴チャット要約です:" + content,
"これは、AI とユーザの過去のチャット要約した前提となるストーリーです:" +
content,
Topic:
"この文の簡潔なテーマを四から五文字で返してください。説明、句読点、感嘆詞、余なテキストは不要です。太字も不要です。テーマがない場合は「雑談」と返してください",
"45文字でこの文の簡潔な主題を返してください。説明、句読点、感嘆詞、余なテキストは無しで。もし主題がない場合は、「おしゃべり」を返してください",
Summarize:
"対話の内容を簡潔に要約し、後続のコンテキストプロンプトとして使用します。200字以内に抑えてください",
"あなたとユーザの会話を簡潔にまとめて、後続のコンテキストプロンプトとして使ってください。200字以内に抑えてください",
},
},
Copy: {
Success: "クリップボードに書き込みました",
Failed: "コピーに失敗しました。クリップボードの権限を付与してください",
},
Download: {
Success: "内容がダウンロードされました",
Failed: "ダウンロードに失敗しました",
Failed: "コピーに失敗しました。クリップボード許可を与えてください",
},
Context: {
Toast: (x: any) => `${x}のプリセットプロンプトが含まれています`,
Edit: "現在の対話設定",
Add: "対話を追加",
Clear: "コンテキストがクリアされました",
Revert: "コンテキストを元に戻す",
},
Plugin: {
Name: "プラグイン",
},
Discovery: {
Name: "発見",
},
FineTuned: {
Sysmessage: "あなたはアシスタントです",
},
SearchChat: {
Name: "検索",
Page: {
Title: "チャット履歴を検索",
Search: "検索キーワードを入力",
NoResult: "結果が見つかりませんでした",
NoData: "データがありません",
Loading: "読み込み中",
SubTitle: (count: number) => `${count} 件の結果が見つかりました`,
},
Item: {
View: "表示",
},
Toast: (x: any) => `キャラクターが ${x}設定されました`,
Edit: "キャラクタープリセットとモデル設定",
Add: "追加",
},
Plugin: { Name: "プラグイン" },
FineTuned: { Sysmessage: "あなたはアシスタントです" },
Mask: {
Name: "マスク",
Name: "キャラクタープリセット",
Page: {
Title: "プリセットキャラクターマスク",
SubTitle: (count: number) => `${count}のプリセットキャラクター定義`,
Search: "キャラクターマスクを検索",
Create: "新規作成",
Title: "キャラクタープリセット",
SubTitle: (count: number) => `${count}見つかりました。`,
Search: "検索",
Create: "新規",
},
Item: {
Info: (count: number) => `${count} 件のプリセット対話が含まれています`,
Chat: "話",
View: "表示",
Info: (count: number) => `包含 ${count} 条预设对话`,
Chat: "話",
View: "詳細",
Edit: "編集",
Delete: "削除",
DeleteConfirm: "削除してもよろしいですか?",
DeleteConfirm: "本当に削除しますか?",
},
EditModal: {
Title: (readonly: boolean) =>
`プリセットマスクの編集 ${readonly ? "(読み取り専用)" : ""}`,
Download: "プリセットをダウンロード",
Clone: "プリセットをクローン",
`キャラクタープリセット編集 ${readonly ? "(読み取り専用)" : ""}`,
Download: "ダウンロード",
Clone: "複製",
},
Config: {
Avatar: "キャラクターアバター",
Name: "キャラクター",
Avatar: "キャラクターのアイコン",
Name: "キャラクターの名前",
Sync: {
Title: "グローバル設定を使用",
SubTitle: "現在の対話でグローバルモデル設定を使用するかどうか",
Title: "グローバル設定を利用する",
SubTitle: "このチャットでグローバル設定を利用します。",
Confirm:
"現在の対話のカスタム設定が自動的に上書きされます。グローバル設定を有効にしてもよろしいですか?",
"カスタム設定を上書きしてグローバル設定を使用します、よろしいですか?",
},
HideContext: {
Title: "プリセット対話を非表示",
SubTitle:
"非表示にすると、プリセット対話はチャット画面に表示されません",
},
Share: {
Title: "このマスクを共有",
SubTitle: "このマスクの直リンクを生成",
Action: "リンクをコピー",
Title: "キャラクター設定を表示しない",
SubTitle: "チャット画面でのキャラクター設定を非表示にします。",
},
},
},
NewChat: {
Return: "戻る",
Skip: "直接開始",
NotShow: "今後表示しない",
ConfirmNoShow:
"無効にしてもよろしいですか?無効にした後、設定でいつでも再度有効にできます。",
Title: "マスクを選択",
SubTitle: "今すぐ始めよう、マスクの背後にある魂と思考の衝突",
More: "すべて表示",
},
URLCommand: {
Code: "リンクにアクセスコードが含まれています。自動入力しますか?",
Settings: "リンクにプリセット設定が含まれています。自動入力しますか?",
Skip: "スキップ",
Title: "キャラクター",
SubTitle: "さあ、AIにキャラクターを設定して会話を始めてみましょう",
More: "もっと探す",
NotShow: "今後は表示しない",
ConfirmNoShow: "いつでも設定から有効化できます。",
},
UI: {
Confirm: "確認",
Cancel: "キャンセル",
Close: "閉じる",
Create: "新規作成",
Create: "新規",
Edit: "編集",
Export: "エクスポート",
Import: "インポート",
Sync: "同期",
Config: "設定",
},
Exporter: {
Description: {
Title: "コンテキストをクリアした後のメッセージのみが表示されます",
},
Model: "モデル",
Messages: "メッセージ",
Topic: "テーマ",
Topic: "トピック",
Time: "時間",
},
};

View File

@@ -1,258 +1,115 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
import type { PartialLocaleType } from "./index";
const ko: PartialLocaleType = {
WIP: "곧 출시 예정...",
Error: {
Unauthorized: isApp
? "유효하지 않은 API 키가 감지되었습니다. [설정](/#/settings) 페이지에서 API 키가 올바르게 구성되었는지 확인하십시오."
: "잘못된 접근 비밀번호이거나 비밀번호가 비어 있습니다. [로그인](/#/auth) 페이지에서 올바른 접근 비밀번호를 입력하거나 [설정](/#/settings) 페이지에서 OpenAI API 키를 입력하십시오.",
},
Auth: {
Title: "비밀번호 필요",
Tips: "관리자가 비밀번호 인증을 활성화했습니다. 아래에 접근 코드를 입력하십시오.",
SubTips: "또는 OpenAI 또는 Google API 키를 입력하십시오.",
Input: "여기에 접근 코드를 입력하십시오.",
Confirm: "확인",
Later: "나중에 하기",
Unauthorized:
"권한이 없습니다. 설정 페이지에서 액세스 코드를 [입력하세요](/#/auth).",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} 개의 대화`,
ChatItemCount: (count: number) => `${count}개의 메시지`,
},
Chat: {
SubTitle: (count: number) => ` ${count} 개의 대화`,
EditMessage: {
Title: "메시지 기록 편집",
Topic: {
Title: "채팅 주제",
SubTitle: "현재 채팅 주제 변경",
},
},
SubTitle: (count: number) => `ChatGPT와의 ${count}개의 메시지`,
Actions: {
ChatList: "메시지 목록 보기",
CompressedHistory: "압축된 히스토리 프롬프트 보기",
Export: "채팅 기록 내보내기",
ChatList: "채팅 목록으로 이동",
CompressedHistory: "압축된 기억력 메모리 프롬프트",
Export: "모든 메시지를 Markdown으로 내보내기",
Copy: "복사",
Stop: "지",
Stop: "지",
Retry: "다시 시도",
Pin: "고정",
PinToastContent: "1 개의 대화를 프롬프트에 고정했습니다.",
PinToastAction: "보기",
Delete: "삭제",
Edit: "편집",
},
Commands: {
new: "새 채팅",
newm: "마스크에서 새 채팅",
next: "다음 채팅",
prev: "이전 채팅",
clear: "컨텍스트 지우기",
del: "채팅 삭제",
},
InputActions: {
Stop: "응답 중지",
ToBottom: "최신으로 스크롤",
Theme: {
auto: "자동 테마",
light: "라이트 모드",
dark: "다크 모드",
},
Prompt: "빠른 명령",
Masks: "모든 마스크",
Clear: "채팅 지우기",
Settings: "채팅 설정",
UploadImage: "이미지 업로드",
},
Rename: "채팅 이름 변경",
Typing: "입력 중",
Typing: "입력 중...",
Input: (submitKey: string) => {
var inputHints = `${submitKey} 전송`;
var inputHints = `${submitKey}를 눌러 보내기`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter 줄 바꿈";
inputHints += ", Shift + Enter 줄 바꿈";
}
return inputHints + "/ 자동 완성,: 명령어 입력";
return inputHints + ", 프롬프트 검색을 위해 / 입력";
},
Send: "전송",
Send: "보내기",
Config: {
Reset: "기억 지우기",
Reset: "기본값으로 재설정",
SaveAs: "마스크로 저장",
},
IsContext: "프롬프트 설정",
},
Export: {
Title: "채팅 기록 공유",
Title: "모든 메시지",
Copy: "모두 복사",
Download: "파일 다운로드",
Share: "ShareGPT에 공유",
MessageFromYou: "사용자",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "내보내기 형식",
SubTitle: "Markdown 텍스트 또는 PNG 이미지로 내보낼 수 있습니다.",
},
IncludeContext: {
Title: "프롬프트 컨텍스트 포함",
SubTitle: "메시지에 프롬프트 컨텍스트를 표시할지 여부",
},
Steps: {
Select: "선택",
Preview: "미리보기",
},
Image: {
Toast: "스크린샷 생성 중",
Modal: "길게 누르거나 오른쪽 클릭하여 이미지를 저장하십시오.",
},
},
Select: {
Search: "메시지 검색",
All: "모두 선택",
Latest: "최근 몇 개",
Clear: "선택 지우기",
Download: "다운로드",
MessageFromYou: "나의 메시지",
MessageFromChatGPT: "ChatGPT의 메시지",
},
Memory: {
Title: "기록 요약",
EmptyContent: "대화 내용이 너무 짧아 요약할 필요 없음",
Send: "자동으로 채팅 기록을 압축하여 컨텍스트로 전송",
Copy: "요약 복사",
Reset: "[사용되지 않음]",
ResetConfirm: "기록 요약을 지우겠습니까?",
Title: "기억 프롬프트",
EmptyContent: "아직 내용이 없습니다.",
Send: "기억 보내기",
Copy: "기억 복사",
Reset: "세션 재설정",
ResetConfirm:
"재설정하면 현재 대화 기록과 기억력이 삭제됩니다. 정말 재설정하시겠습니까?",
},
Home: {
NewChat: "새 채팅",
NewChat: "새로운 채팅",
DeleteChat: "선택한 대화를 삭제하시겠습니까?",
DeleteToast: "대화가 삭제되었습니다.",
DeleteToast: "채팅이 삭제되었습니다.",
Revert: "되돌리기",
},
Settings: {
Title: "설정",
SubTitle: "모든 설정 옵션",
SubTitle: "모든 설정",
Danger: {
Reset: {
Title: "모든 설정 초기화",
SubTitle: "모든 설정 항목을 기본값으로 초기화",
Action: "지금 초기화",
Confirm: "모든 설정을 초기화하시겠습니까?",
},
Clear: {
Title: "모든 데이터 지우기",
SubTitle: "모든 채팅 및 설정 데이터 지우기",
Action: "지금 지우기",
Confirm: "모든 채팅 및 설정 데이터를 지우시겠습니까?",
},
},
Lang: {
Name: "Language", // 주의: 새 번역을 추가하려면 이 값을 번역하지 말고 그대로 유지하세요.
All: "모든 언어",
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "All Languages",
},
Avatar: "아바타",
FontSize: {
Title: "글꼴 크기",
SubTitle: "채팅 내용의 글꼴 크기",
},
FontFamily: {
Title: "채팅 폰트",
SubTitle: "채팅 내용의 폰트, 비워 두면 글로벌 기본 폰트를 적용",
Placeholder: "폰트 이름",
SubTitle: "채팅 내용의 글꼴 크기 조정",
},
InjectSystemPrompts: {
Title: "시스템 수준 프롬프트 입",
Title: "시스템 프롬프트 입",
SubTitle:
"각 요청 메시지 목록의 시작 부분에 ChatGPT 시스템 프롬프트를 강제로 추가",
"각 요청 메시지 목록의 시작에 ChatGPT 시스템 프롬프트를 강제로 추가합니다",
},
InputTemplate: {
Title: "사용자 입력 전처리",
SubTitle: "사용자의 최신 메시지가 이 템플릿에 채워집니다.",
},
Update: {
Version: (x: string) => `현재 버전: ${x}`,
IsLatest: "최신 버전입니다.",
Version: (x: string) => `버전: ${x}`,
IsLatest: "최신 버전",
CheckUpdate: "업데이트 확인",
IsChecking: "업데이트 확인 중...",
FoundUpdate: (x: string) => `새 버전 발견: ${x}`,
GoToUpdate: "업데이트로 이동",
GoToUpdate: "업데이트",
},
SendKey: "전송 키",
Theme: "테마",
TightBorder: "테두리 없는 모드",
TightBorder: "조밀한 테두리",
SendPreviewBubble: {
Title: "미리보기 버블",
SubTitle: "미리보기 버블에서 Markdown 콘텐츠 미리보기",
},
AutoGenerateTitle: {
Title: "제목 자동 생성",
SubTitle: "대화 내용에 따라 적절한 제목 생성",
},
Sync: {
CloudState: "클라우드 데이터",
NotSyncYet: "아직 동기화되지 않았습니다.",
Success: "동기화 성공",
Fail: "동기화 실패",
Config: {
Modal: {
Title: "클라우드 동기화 구성",
Check: "사용 가능성 확인",
},
SyncType: {
Title: "동기화 유형",
SubTitle: "선호하는 동기화 서버 선택",
},
Proxy: {
Title: "프록시 사용",
SubTitle:
"브라우저에서 동기화할 때 프록시를 활성화하여 교차 출처 제한을 피해야 함",
},
ProxyUrl: {
Title: "프록시 주소",
SubTitle: "이 프로젝트에서 제공하는 교차 출처 프록시만 해당",
},
WebDav: {
Endpoint: "WebDAV 주소",
UserName: "사용자 이름",
Password: "비밀번호",
},
UpStash: {
Endpoint: "UpStash Redis REST URL",
UserName: "백업 이름",
Password: "UpStash Redis REST Token",
},
},
LocalState: "로컬 데이터",
Overview: (overview: any) => {
return `${overview.chat} 회의 대화, ${overview.message} 개의 메시지, ${overview.prompt} 개의 프롬프트, ${overview.mask} 개의 마스크`;
},
ImportFailed: "가져오기 실패",
Title: "미리 보기 버블 전송",
SubTitle: "버블에서 마크다운 미리 보기",
},
Mask: {
Splash: {
Title: "마스크 시작 페이지",
SubTitle: "새 채팅 시 마스크 시작 페이지 표시",
},
Builtin: {
Title: "내장 마스크 숨기기",
SubTitle: "모든 마스크 목록에서 내장 마스크 숨기기",
Title: "마스크 시작 화면",
SubTitle: "새로운 채팅 시작 전에 마스크 시작 화면 표시",
},
},
Prompt: {
Disable: {
Title: "프롬프트 자동 완성 비활성화",
SubTitle: "입력 상자 시작 부분에 / 를 입력하여 자동 완성 활성화",
Title: "자동 완성 비활성화",
SubTitle: "자동 완성을 활성화하려면 /를 입력하세요.",
},
List: "사용자 정의 프롬프트 목록",
List: "프롬프트 목록",
ListCount: (builtin: number, custom: number) =>
`내장 ${builtin} 개, 사용자 정의 ${custom} `,
`내장 ${builtin}개, 사용자 정의 ${custom}`,
Edit: "편집",
Modal: {
Title: "프롬프트 목록",
Add: "새로 만들기",
Add: "추가",
Search: "프롬프트 검색",
},
EditModal: {
@@ -260,293 +117,116 @@ const ko: PartialLocaleType = {
},
},
HistoryCount: {
Title: "히스토리 메시지 수",
SubTitle: "각 요청에 포함된 히스토리 메시지 수",
Title: "첨부된 메시지 수",
SubTitle: "요청당 첨부된 전송된 메시지 수",
},
CompressThreshold: {
Title: "히스토리 메시지 길이 압축 임계값",
SubTitle: "압축되지 않은 히스토리 메시지가 이 값을 초과하면 압축 수행",
Title: "기록 압축 임계값",
SubTitle: "압축 메시지 길이가 임계값을 초과하면 압축",
},
Usage: {
Title: "잔액 조회",
Title: "계정 잔액",
SubTitle(used: any, total: any) {
return `이번 달 사용된 금액: $${used},총 구독 금액: $${total}`;
return `이번 달 사용${used}, 구독 ${total}`;
},
IsChecking: "확인 중...",
Check: "다시 확인",
NoAccess: "잔액을 보려면 API 키 또는 접근 비밀번호를 입력하십시오.",
Check: "확인",
NoAccess: "잔액 확인을 위해 API 키를 입력하세요.",
},
Access: {
AccessCode: {
Title: "접근 비밀번호",
SubTitle: "관리자가 암호화된 접근을 활성화했습니다.",
Placeholder: "접근 비밀번호를 입력하십시오.",
},
CustomEndpoint: {
Title: "커스텀 엔드포인트",
SubTitle: "커스텀 Azure 또는 OpenAI 서비스를 사용할지 여부",
},
Provider: {
Title: "모델 서비스 제공업체",
SubTitle: "다른 서비스 제공업체로 전환",
},
OpenAI: {
ApiKey: {
Title: "API 키",
SubTitle: "커스텀 OpenAI 키를 사용하여 비밀번호 접근 제한 우회",
Placeholder: "OpenAI API 키",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "기본 주소 외에 http(s)://을 포함해야 함",
},
},
Azure: {
ApiKey: {
Title: "엔드포인트 키",
SubTitle: "커스텀 Azure 키를 사용하여 비밀번호 접근 제한 우회",
Placeholder: "Azure API 키",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "예: ",
},
ApiVerion: {
Title: "API 버전 (azure api version)",
SubTitle: "특정 부분 버전 선택",
},
},
Anthropic: {
ApiKey: {
Title: "엔드포인트 키",
SubTitle: "커스텀 Anthropic 키를 사용하여 비밀번호 접근 제한 우회",
Placeholder: "Anthropic API 키",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "예: ",
},
ApiVerion: {
Title: "API 버전 (claude api version)",
SubTitle: "특정 API 버전 입력",
},
},
Google: {
ApiKey: {
Title: "API 키",
SubTitle: "Google AI에서 API 키를 가져오세요.",
Placeholder: "Google AI Studio API 키 입력",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "예: ",
},
ApiVersion: {
Title: "API 버전 (gemini-pro 전용)",
SubTitle: "특정 API 버전 선택",
},
GoogleSafetySettings: {
Title: "Google 안전 필터링 수준",
SubTitle: "콘텐츠 필터링 수준 설정",
},
},
Baidu: {
ApiKey: {
Title: "API 키",
SubTitle: "커스텀 Baidu API 키 사용",
Placeholder: "Baidu API 키",
},
SecretKey: {
Title: "Secret 키",
SubTitle: "커스텀 Baidu Secret 키 사용",
Placeholder: "Baidu Secret 키",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "커스터마이즈는 .env에서 설정",
},
},
ByteDance: {
ApiKey: {
Title: "엔드포인트 키",
SubTitle: "커스텀 ByteDance API 키 사용",
Placeholder: "ByteDance API 키",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "예: ",
},
},
Alibaba: {
ApiKey: {
Title: "엔드포인트 키",
SubTitle: "커스텀 Alibaba Cloud API 키 사용",
Placeholder: "Alibaba Cloud API 키",
},
Endpoint: {
Title: "엔드포인트 주소",
SubTitle: "예: ",
},
},
CustomModel: {
Title: "커스텀 모델 이름",
SubTitle: "커스텀 모델 옵션 추가, 영어 쉼표로 구분",
},
},
Model: "모델 (model)",
Model: "모델",
Temperature: {
Title: "무작위성 (temperature)",
SubTitle: "값이 클수록 응답이 더 무작위",
},
TopP: {
Title: "탑 P 샘플링 (top_p)",
SubTitle: "무작위성과 유사하지만, 무작위성과 함께 변경하지 마십시오.",
Title: "온도 (temperature)",
SubTitle: "값이 클수록 더 무작위한 출력이 생성됩니다.",
},
MaxTokens: {
Title: "단일 응답 제한 (max_tokens)",
SubTitle: "단일 상호작용에 사용되는 최대 토큰 수",
Title: "최대 토큰 수 (max_tokens)",
SubTitle: "입력 토큰과 생성된 토큰의 최대 길이",
},
PresencePenalty: {
Title: "주제 신선도 (presence_penalty)",
SubTitle: "값이 클수록 새로운 주제로 확장할 가능성이 높",
Title: "존재 페널티 (presence_penalty)",
SubTitle: "값이 클수록 새로운 주제에 대해 대화할 가능성이 높아집니다.",
},
FrequencyPenalty: {
Title: "빈도 벌점 (frequency_penalty)",
SubTitle: "값이 클수록 중복 단어 감소 가능성 높음",
Title: "빈도 페널티(frequency penalty)",
SubTitle: "값이 클수록 같은 줄이 반복될 가능성이 줄어듭니다.",
},
},
Store: {
DefaultTopic: "새 채팅",
BotHello: "무엇을 도와드릴까요?",
Error: "오류가 발생했습니다. 나중에 다시 시도해 주세요.",
DefaultTopic: "새 대화",
BotHello: "안녕하세요! 오늘 도움이 필요하신가요?",
Error: "문제가 발생했습니다. 나중에 다시 시도해주세요.",
Prompt: {
History: (content: string) => "이것은 이전 채팅 요약입니다: " + content,
History: (content: string) =>
"이것은 AI와 사용자 간의 대화 기록을 요약한 내용입니다: " + content,
Topic:
"네 글자에서 다섯 글자로 이 문장의 간략한 주제를 반환하세요. 설명이나 문장 부호, 어미, 불필요한 텍스트, 굵은 글씨는 필요 없습니다. 주제가 없다면 '잡담'이라고만 반환하세요.",
"다음과 같이 대화 내용을 요약하는 4~5단어 제목을 생성해주세요. 따옴표, 구두점, 인용부호, 기호 또는 추가 텍스트를 제거하십시오. 따옴표로 감싸진 부분을 제거하십시오.",
Summarize:
"대화 내용을 간략히 요약하여 후속 컨텍스트 프롬프트로 사용하세요. 200자 이내로 작성하세요.",
"200단어 이내로 저희 토론을 간략히 요약하여 앞으로의 맥락으로 사용할 수 있는 프롬프트로 만들어주세요.",
},
},
Copy: {
Success: "클립보드에 복사되었습니다.",
Failed: "복사 실패, 클립보드 권한을 부여해주세요.",
},
Download: {
Success: "내용이 디렉토리에 다운로드되었습니다.",
Failed: "다운로드 실패.",
Failed: "복사 실패, 클립보드 접근 권한을 허용해주세요.",
},
Context: {
Toast: (x: any) => ` ${x} 개의 프리셋 프롬프트 포함됨`,
Edit: "현재 대화 설정",
Add: "대화 추가",
Clear: "컨텍스트가 지워졌습니다.",
Revert: "컨텍스트 복원",
Toast: (x: any) => `컨텍스트 프롬프트 ${x}개 사용`,
Edit: "컨텍스트 및 메모리 프롬프트",
Add: "프롬프트 추가",
},
Plugin: {
Name: "플러그인",
},
FineTuned: {
Sysmessage: "당신은 보조자입니다.",
},
SearchChat: {
Name: "검색",
Page: {
Title: "채팅 기록 검색",
Search: "검색어 입력",
NoResult: "결과를 찾을 수 없습니다",
NoData: "데이터가 없습니다",
Loading: "로딩 중",
SubTitle: (count: number) => `${count}개의 결과를 찾았습니다`,
},
Item: {
View: "보기",
},
Sysmessage: "당신은 어시스턴트입니다",
},
Mask: {
Name: "마스크",
Page: {
Title: "프리셋 캐릭터 마스크",
SubTitle: (count: number) => `${count} 개의 프리셋 캐릭터 정의`,
Search: "캐릭터 마스크 검색",
Create: "새로 만들기",
Title: "프롬프트 템플릿",
SubTitle: (count: number) => `${count}개의 프롬프트 템플릿`,
Search: "템플릿 검색",
Create: "생성",
},
Item: {
Info: (count: number) => ` ${count} 개의 프리셋 대화 포함`,
Chat: "대화",
Info: (count: number) => `${count}개의 프롬프롬프트`,
Chat: "채팅",
View: "보기",
Edit: "편집",
Delete: "삭제",
DeleteConfirm: "삭제를 확인하시겠습니까?",
DeleteConfirm: "삭제하시겠습니까?",
},
EditModal: {
Title: (readonly: boolean) =>
`리셋 마스크 편집 ${readonly ? "읽기 전용" : ""}`,
Download: "프리셋 다운로드",
Clone: "프리셋 복제",
`롬프트 템플릿 편집 ${readonly ? "(읽기 전용)" : ""}`,
Download: "다운로드",
Clone: "복제",
},
Config: {
Avatar: "캐릭터 아바타",
Name: "캐릭터 이름",
Sync: {
Title: "전역 설정 사용",
SubTitle: "현재 대화가 전역 모델 설정을 사용하는지 여부",
Confirm:
"현재 대화의 사용자 정의 설정이 자동으로 덮어쓰여질 것입니다. 전역 설정을 활성화하시겠습니까?",
},
HideContext: {
Title: "프리셋 대화 숨기기",
SubTitle: "숨기면 프리셋 대화가 채팅 화면에 나타나지 않습니다.",
},
Share: {
Title: "이 마스크 공유하기",
SubTitle: "이 마스크의 직접 링크 생성",
Action: "링크 복사",
},
Avatar: " 아바타",
Name: " 이름",
},
},
NewChat: {
Return: "돌아가기",
Skip: "바로 시작",
NotShow: "다시 보지 않기",
ConfirmNoShow:
"비활성화하시겠습니까? 비활성화 후 언제든지 설정에서 다시 활성화할 수 있습니다.",
Skip: "건너뛰기",
Title: "마스크 선택",
SubTitle: "지금 시작하여 마스크 뒤의 사고와 교류해보세요.",
More: "모두 보기",
},
URLCommand: {
Code: "링크에 액세스 코드가 포함되어 있습니다. 자동으로 입력하시겠습니까?",
Settings:
"링크에 프리셋 설정이 포함되어 있습니다. 자동으로 입력하시겠습니까?",
SubTitle: "마스크 뒤의 영혼과 대화하세요",
More: " 보기",
NotShow: "다시 표시하지 않음",
ConfirmNoShow:
"비활성화하시겠습니까? 나중에 설정에서 다시 활성화할 수 있습니다.",
},
UI: {
Confirm: "확인",
Cancel: "취소",
Close: "닫기",
Create: "새로 만들기",
Create: "생성",
Edit: "편집",
Export: "내보내기",
Import: "가져오기",
Sync: "동기화",
Config: "구성",
},
Exporter: {
Description: {
Title: "컨텍스트가 지워진 후의 메시지만 표시됩니다.",
},
Model: "모델",
Messages: "메시지",
Topic: "주제",

View File

@@ -1,572 +1,158 @@
import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
const no: PartialLocaleType = {
WIP: "Arbeid pågår ...",
Error: {
Unauthorized: isApp
? "Ugyldig API-nøkkel oppdaget. Gå til [innstillinger](/#/settings) for å sjekke om API-nøkkelen er riktig konfigurert."
: "Adgangskoden er feil eller tom. Gå til [innlogging](/#/auth) for å oppgi riktig adgangskode, eller fyll inn din egen OpenAI API-nøkkel på [innstillinger](/#/settings) siden.",
},
Auth: {
Title: "Passord påkrevd",
Tips: "Administrator har aktivert passordbeskyttelse. Vennligst skriv inn tilgangskoden nedenfor",
SubTips: "Eller skriv inn din OpenAI eller Google API-nøkkel",
Input: "Skriv tilgangskoden her",
Confirm: "Bekreft",
Later: "Kom tilbake senere",
Unauthorized:
"Du har ikke tilgang. [Vennlig oppgi tildelt adgangskode](/#/auth).",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} samtaler`,
ChatItemCount: (count: number) => `${count} meldinger`,
},
Chat: {
SubTitle: (count: number) => `Totalt ${count} samtaler`,
EditMessage: {
Title: "Rediger meldingshistorikk",
Topic: {
Title: "Samtaleemne",
SubTitle: "Endre nåværende samtaleemne",
},
},
SubTitle: (count: number) => `${count} meldinger med ChatGPT`,
Actions: {
ChatList: "Vis meldingsliste",
CompressedHistory: "Vis komprimert historikk",
Export: "Eksporter samtaler",
ChatList: "Gå til chatlisten",
CompressedHistory: "Komprimert historikk for instrukser",
Export: "Eksporter alle meldinger i markdown-format",
Copy: "Kopier",
Stop: "Stopp",
Retry: "Prøv igjen",
Pin: "Fest",
PinToastContent:
"1 samtale er festet til forhåndsdefinerte oppfordringer",
PinToastAction: "Se",
Delete: "Slett",
Edit: "Rediger",
},
Commands: {
new: "Ny samtale",
newm: "Start samtale fra maske",
next: "Neste samtale",
prev: "Forrige samtale",
clear: "Rydd kontekst",
del: "Slett samtale",
},
InputActions: {
Stop: "Stopp respons",
ToBottom: "Rull til nyeste",
Theme: {
auto: "Automatisk tema",
light: "Lyst tema",
dark: "Mørkt tema",
},
Prompt: "Hurtigkommando",
Masks: "Alle masker",
Clear: "Rydd samtale",
Settings: "Samtaleinnstillinger",
UploadImage: "Last opp bilde",
},
Rename: "Gi nytt navn til samtale",
Typing: "Skriver…",
Rename: "Gi nytt navn",
Typing: "Skriver …",
Input: (submitKey: string) => {
var inputHints = `${submitKey} send`;
var inputHints = `${submitKey} for å sende`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter for linjeskift";
inputHints += ", Shift + Enter for å omgi";
}
return (
inputHints + "/ for å utløse autoutfylling, : for å utløse kommando"
);
return inputHints + ", / for å søke instrukser";
},
Send: "Send",
Config: {
Reset: "Fjern minne",
SaveAs: "Lagre som maske",
},
IsContext: "Forhåndsdefinerte oppfordringer",
},
Export: {
Title: "Del samtalehistorikk",
Copy: "Kopier alt",
Download: "Last ned fil",
Share: "Del til ShareGPT",
MessageFromYou: "Bruker",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Eksporterformat",
SubTitle: "Kan eksporteres som Markdown-tekst eller PNG-bilde",
},
IncludeContext: {
Title: "Inkluder maske kontekst",
SubTitle: "Skal maske kontekst vises i meldinger",
},
Steps: {
Select: "Velg",
Preview: "Forhåndsvis",
},
Image: {
Toast: "Genererer skjermbilde",
Modal: "Langtrykk eller høyreklikk for å lagre bilde",
},
},
Select: {
Search: "Søk meldinger",
All: "Velg alle",
Latest: "Siste meldinger",
Clear: "Fjern valg",
Title: "Alle meldinger",
Copy: "Kopiere alle",
Download: "Last ned",
MessageFromYou: "Melding fra deg",
MessageFromChatGPT: "Melding fra ChatGPT",
},
Memory: {
Title: "Historisk sammendrag",
EmptyContent: "Samtaleinnholdet er for kort, ingen oppsummering nødvendig",
Send: "Automatisk komprimere samtalehistorikk og sende som kontekst",
Copy: "Kopier sammendrag",
Reset: "[unused]",
ResetConfirm: "Er du sikker på at du vil tømme historisk sammendrag?",
Title: "Minneinstruks",
EmptyContent: "Ingen sålant.",
Send: "Send minne",
Copy: "Kopiere minne",
Reset: "Nulstill sesjon",
ResetConfirm:
"Om du nillstiller vil du slette hele historikken. Er du sikker på at du vil nullstille?",
},
Home: {
NewChat: "Ny samtale",
DeleteChat: "Er du sikker på at du vil slette den valgte samtalen?",
NewChat: "Ny chat",
DeleteChat: "Bekreft for å slette det valgte dialogen",
DeleteToast: "Samtale slettet",
Revert: "Angre",
Revert: "Tilbakestill",
},
Settings: {
Title: "Innstillinger",
SubTitle: "Alle innstillingsalternativer",
SubTitle: "Alle innstillinger",
Danger: {
Reset: {
Title: "Tilbakestill alle innstillinger",
SubTitle:
"Tilbakestill alle innstillingsalternativer til standardverdier",
Action: "Tilbakestill nå",
Confirm: "Bekreft tilbakestilling av alle innstillinger?",
},
Clear: {
Title: "Slett alle data",
SubTitle: "Slett alle samtaler og innstillingsdata",
Action: "Slett nå",
Confirm: "Bekreft sletting av alle samtaler og innstillingsdata?",
},
},
Lang: {
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Alle språk",
},
Avatar: "Profilbilde",
Avatar: "Avatar",
FontSize: {
Title: "Skriftstørrelse",
SubTitle: "Skriftstørrelse for samtaleinnhold",
},
FontFamily: {
Title: "Chat-skrifttype",
SubTitle:
"Skrifttypen for chatinnhold, la stå tom for å bruke global standardskrifttype",
Placeholder: "Skriftnavn",
Title: "Fontstørrelsen",
SubTitle: "Juster fontstørrelsen for samtaleinnholdet.",
},
InjectSystemPrompts: {
Title: "Injiser systemprompter",
Title: "Sett inn systemprompter",
SubTitle:
"Tving inn et systemprompt som simulerer ChatGPT i starten av hver forespørsel",
"Tving tillegg av en simulert ChatGPT-systemprompt i begynnelsen av meldingslisten for hver forespørsel",
},
InputTemplate: {
Title: "Forhåndsbehandling av brukerinput",
SubTitle:
"Den nyeste meldingen fra brukeren vil bli fylt ut i denne malen",
},
Update: {
Version: (x: string) => `Nåværende versjon: ${x}`,
IsLatest: "Er den nyeste versjonen",
CheckUpdate: "Sjekk oppdateringer",
IsChecking: "Sjekker oppdateringer...",
FoundUpdate: (x: string) => `Ny versjon oppdaget: ${x}`,
GoToUpdate: "Gå til oppdatering",
Version: (x: string) => `Versjon: ${x}`,
IsLatest: "Siste versjon",
CheckUpdate: "Se etter oppdatering",
IsChecking: "Ser etter oppdatering ...",
FoundUpdate: (x: string) => `Fant ny versjon: ${x}`,
GoToUpdate: "Oppdater",
},
SendKey: "Send-knapp",
SendKey: "Send nøkkel",
Theme: "Tema",
TightBorder: "Ingen ramme-modus",
SendPreviewBubble: {
Title: "Forhåndsvisningsboble",
SubTitle: "Forhåndsvis Markdown-innhold i en forhåndsvisningsboble",
},
AutoGenerateTitle: {
Title: "Automatisk generere tittel",
SubTitle: "Generer en passende tittel basert på samtaleinnholdet",
},
Sync: {
CloudState: "Skydatasynkronisering",
NotSyncYet: "Har ikke blitt synkronisert ennå",
Success: "Synkronisering vellykket",
Fail: "Synkronisering mislyktes",
Config: {
Modal: {
Title: "Konfigurer sky-synkronisering",
Check: "Sjekk tilgjengelighet",
},
SyncType: {
Title: "Synkroniseringstype",
SubTitle: "Velg ønsket synkroniseringsserver",
},
Proxy: {
Title: "Aktiver proxy",
SubTitle:
"Når du synkroniserer i nettleseren, må proxy være aktivert for å unngå CORS-restriksjoner",
},
ProxyUrl: {
Title: "Proxy-URL",
SubTitle: "Kun for prosjektets innebygde CORS-proxy",
},
WebDav: {
Endpoint: "WebDAV-adresse",
UserName: "Brukernavn",
Password: "Passord",
},
UpStash: {
Endpoint: "UpStash Redis REST-URL",
UserName: "Sikkerhetskopinavn",
Password: "UpStash Redis REST-token",
},
},
LocalState: "Lokal data",
Overview: (overview: any) => {
return `${overview.chat} samtaler, ${overview.message} meldinger, ${overview.prompt} oppfordringer, ${overview.mask} masker`;
},
ImportFailed: "Import mislyktes",
},
Mask: {
Splash: {
Title: "Maskestartside",
SubTitle: "Vis maskestartside når du oppretter en ny samtale",
},
Builtin: {
Title: "Skjul innebygde masker",
SubTitle: "Skjul innebygde masker i alle maskelister",
},
},
TightBorder: "Stram innramming",
Prompt: {
Disable: {
Title: "Deaktiver automatisk fullføring av oppfordringer",
SubTitle: "Skriv / i tekstboksen for å utløse automatisk fullføring",
Title: "Skru av autofullfør",
SubTitle: "Skriv / for å trigge autofullfør",
},
List: "Egendefinerte oppfordringer",
List: "Instruksliste",
ListCount: (builtin: number, custom: number) =>
`Innebygde ${builtin}, brukerdedefinerte ${custom}`,
Edit: "Rediger",
`${builtin} innebygde, ${custom} brukerdefinerte`,
Edit: "Endre",
Modal: {
Title: "Oppfordringsliste",
Add: "Ny",
Search: "Søk oppfordringer",
},
EditModal: {
Title: "Rediger oppfordring",
Title: "Instruksliste",
Add: "Legg til",
Search: "Søk instrukser",
},
},
HistoryCount: {
Title: "Antall historiske meldinger",
SubTitle: "Antall historiske meldinger som sendes med hver forespørsel",
Title: "Tall på tilhørende meldinger",
SubTitle: "Antall sendte meldinger tilknyttet hver spørring",
},
CompressThreshold: {
Title: "Kompressterskel for historiske meldinger",
Title: "Terskeverdi for komprimering av historikk",
SubTitle:
"Når ukomprimerte historiske meldinger overskrider denne verdien, vil de bli komprimert",
"Komprimer dersom ikke-komprimert lengde på meldinger overskrider denne verdien",
},
Usage: {
Title: "Saldoforespørsel",
Title: "Saldo for konto",
SubTitle(used: any, total: any) {
return `Brukt denne måneden $${used}, total abonnementsbeløp $${total}`;
return `Brukt denne måneden $${used}, abonnement $${total}`;
},
IsChecking: "Sjekker...",
Check: "Sjekk på nytt",
NoAccess: "Skriv inn API-nøkkel eller tilgangspassord for å se saldo",
IsChecking: "Sjekker ...",
Check: "Sjekk",
NoAccess: "Skriv inn API-nøkkelen for å sjekke saldo",
},
Access: {
AccessCode: {
Title: "Adgangskode",
SubTitle: "Administrator har aktivert kryptert tilgang",
Placeholder: "Skriv inn tilgangskoden",
},
CustomEndpoint: {
Title: "Egendefinert API",
SubTitle: "Bruk egendefinerte Azure- eller OpenAI-tjenester",
},
Provider: {
Title: "Modelltilbyder",
SubTitle: "Bytt til forskjellige tilbydere",
},
OpenAI: {
ApiKey: {
Title: "API-nøkkel",
SubTitle:
"Bruk egendefinert OpenAI-nøkkel for å omgå passordtilgangsbegrensninger",
Placeholder: "OpenAI API-nøkkel",
},
Endpoint: {
Title: "API-adresse",
SubTitle: "Må inkludere http(s):// utenom standardadresse",
},
},
Azure: {
ApiKey: {
Title: "API-nøkkel",
SubTitle:
"Bruk egendefinert Azure-nøkkel for å omgå passordtilgangsbegrensninger",
Placeholder: "Azure API-nøkkel",
},
Endpoint: {
Title: "API-adresse",
SubTitle: "Eksempel:",
},
ApiVerion: {
Title: "API-versjon (azure api versjon)",
SubTitle: "Velg en spesifikk delversjon",
},
},
Anthropic: {
ApiKey: {
Title: "API-nøkkel",
SubTitle:
"Bruk egendefinert Anthropic-nøkkel for å omgå passordtilgangsbegrensninger",
Placeholder: "Anthropic API-nøkkel",
},
Endpoint: {
Title: "API-adresse",
SubTitle: "Eksempel:",
},
ApiVerion: {
Title: "API-versjon (claude api versjon)",
SubTitle: "Velg en spesifikk API-versjon",
},
},
Google: {
ApiKey: {
Title: "API-nøkkel",
SubTitle: "Hent din API-nøkkel fra Google AI",
Placeholder: "Skriv inn din Google AI Studio API-nøkkel",
},
Endpoint: {
Title: "Endepunktadresse",
SubTitle: "Eksempel:",
},
ApiVersion: {
Title: "API-versjon (kun for gemini-pro)",
SubTitle: "Velg en spesifikk API-versjon",
},
GoogleSafetySettings: {
Title: "Google sikkerhetsfiltreringsnivå",
SubTitle: "Sett innholdsfiltreringsnivå",
},
},
Baidu: {
ApiKey: {
Title: "API-nøkkel",
SubTitle: "Bruk egendefinert Baidu API-nøkkel",
Placeholder: "Baidu API-nøkkel",
},
SecretKey: {
Title: "Hemmelig nøkkel",
SubTitle: "Bruk egendefinert Baidu hemmelig nøkkel",
Placeholder: "Baidu hemmelig nøkkel",
},
Endpoint: {
Title: "API-adresse",
SubTitle:
"Støtter ikke egendefinerte konfigurasjoner. Se .env-konfigurasjon.",
},
},
ByteDance: {
ApiKey: {
Title: "API-nøkkel",
SubTitle: "Bruk egendefinert ByteDance API-nøkkel",
Placeholder: "ByteDance API-nøkkel",
},
Endpoint: {
Title: "API-adresse",
SubTitle: "Eksempel:",
},
},
Alibaba: {
ApiKey: {
Title: "API-nøkkel",
SubTitle: "Bruk egendefinert Alibaba Cloud API-nøkkel",
Placeholder: "Alibaba Cloud API-nøkkel",
},
Endpoint: {
Title: "API-adresse",
SubTitle: "Eksempel:",
},
},
CustomModel: {
Title: "Egendefinert modellnavn",
SubTitle: "Legg til egendefinerte modellalternativer, skill med komma",
},
},
Model: "Modell",
Model: "Model",
Temperature: {
Title: "Tilfeldighet (temperature)",
SubTitle: "Høyere verdi gir mer tilfeldige svar",
},
TopP: {
Title: "Kjerneprøvetaking (top_p)",
SubTitle:
"Ligner på tilfeldighet, men endre ikke sammen med tilfeldighet",
Title: "Temperatur",
SubTitle: "Høyere verdi gir mer kreative svar",
},
MaxTokens: {
Title: "Maksimalt antall tokens per svar (max_tokens)",
SubTitle: "Maksimalt antall tokens brukt i en enkelt interaksjon",
},
PresencePenalty: {
Title: "Emnens ferskhet (presence_penalty)",
SubTitle:
"Høyere verdi gir større sannsynlighet for å utvide til nye emner",
},
FrequencyPenalty: {
Title: "Frekvensstraff (frequency_penalty)",
SubTitle:
"Høyere verdi gir større sannsynlighet for å redusere gjentakende ord",
Title: "Maks tokens",
SubTitle: "Maksimum lengde på tokens for instrukser og svar",
},
},
Store: {
DefaultTopic: "Ny samtale",
BotHello: "Hva kan jeg hjelpe deg med?",
Error: "Noe gikk galt, prøv igjen senere",
BotHello: "Hei! Hva kan jeg hjelpe deg med i dag?",
Error: "Noe gikk galt, vennligst prøv igjen senere.",
Prompt: {
History: (content: string) =>
"Dette er oppsummeringen av historiske samtaler som bakgrunn:" +
"Dette er et sammendrag av chatthistorikken mellom AI-en og brukeren som en oppsummering: " +
content,
Topic:
'Bruk fire til fem ord for å returnere en kort oppsummering av temaet, uten forklaring, uten tegnsetting, uten fyllord, uten ekstra tekst, uten fet skrift. Hvis det ikke er noe tema, returner bare "sladder".',
"Vennligst lag en fire til fem ords tittel som oppsummerer samtalen vår uten innledning, punktsetting, anførselstegn, punktum, symboler eller tillegg tekst. Fjern innrammende anførselstegn.",
Summarize:
"Oppsummer samtalen kort som en kontekstuell prompt for fremtidige referanser, hold det innen 200 tegn",
"Oppsummer diskusjonen vår kort i 200 ord eller mindre for å bruke som en oppfordring til fremtidig sammenheng.",
},
},
Copy: {
Success: "Kopiert til utklippstavlen",
Failed: "Kopiering mislyktes, vennligst gi tillatelse til utklippstavlen",
},
Download: {
Success: "Innholdet er lastet ned til katalogen din.",
Failed: "Nedlasting mislyktes.",
Success: "Kopiert til utklippstavle",
Failed: "Kopiering feilet. Vennligst gi tilgang til utklippstavlen.",
},
Context: {
Toast: (x: any) => `Inneholder ${x} forhåndsinnstilte oppfordringer`,
Edit: "Nåværende samtaleinnstillinger",
Add: "Legg til en ny samtale",
Clear: "Konteksten er tømt",
Revert: "Gjenopprett konteksten",
},
Plugin: {
Name: "Plugin",
},
FineTuned: {
Sysmessage: "Du er en assistent",
},
SearchChat: {
Name: "Søk",
Page: {
Title: "Søk i chatthistorikk",
Search: "Skriv inn søkeord",
NoResult: "Ingen resultater funnet",
NoData: "Ingen data",
Loading: "Laster inn",
SubTitle: (count: number) => `Fant ${count} resultater`,
},
Item: {
View: "Vis",
},
},
Mask: {
Name: "Maske",
Page: {
Title: "Forhåndsdefinerte rollemasker",
SubTitle: (count: number) =>
`${count} forhåndsdefinerte rolledefinisjoner`,
Search: "Søk etter rollemasker",
Create: "Opprett ny",
},
Item: {
Info: (count: number) => `Inneholder ${count} forhåndsdefinerte samtaler`,
Chat: "Samtale",
View: "Vis",
Edit: "Rediger",
Delete: "Slett",
DeleteConfirm: "Bekreft sletting?",
},
EditModal: {
Title: (readonly: boolean) =>
`Rediger forhåndsdefinert maske ${readonly ? "kun lesing" : ""}`,
Download: "Last ned forhåndsdefinert",
Clone: "Kopier forhåndsdefinert",
},
Config: {
Avatar: "Rollebilde",
Name: "Rolle navn",
Sync: {
Title: "Bruk globale innstillinger",
SubTitle: "Bruker nåværende samtale globale modellinnstillinger",
Confirm:
"De tilpassede innstillingene for den nåværende samtalen vil bli overskrevet automatisk. Bekreft at du vil bruke globale innstillinger?",
},
HideContext: {
Title: "Skjul forhåndsdefinerte samtaler",
SubTitle:
"Når skjult, vil forhåndsdefinerte samtaler ikke vises i chat-grensesnittet",
},
Share: {
Title: "Del denne masken",
SubTitle: "Generer en direkte lenke til denne masken",
Action: "Kopier lenke",
},
},
},
NewChat: {
Return: "Tilbake",
Skip: "Start direkte",
NotShow: "Vis ikke igjen",
ConfirmNoShow:
"Bekreft deaktivering? Du kan aktivere det igjen i innstillingene når som helst.",
Title: "Velg en maske",
SubTitle: "Start nå, og få tanker som kolliderer med sjelen bak masken",
More: "Se alle",
},
URLCommand: {
Code: "Oppdaget at lenken allerede inneholder tilgangskode. Ønsker du å fylle den ut automatisk?",
Settings:
"Oppdaget at lenken inneholder forhåndsinnstillinger. Ønsker du å fylle dem ut automatisk?",
},
UI: {
Confirm: "Bekreft",
Cancel: "Avbryt",
Close: "Lukk",
Create: "Opprett",
Edit: "Rediger",
Export: "Eksporter",
Import: "Importer",
Sync: "Synkroniser",
Config: "Konfigurer",
Toast: (x: any) => `Med ${x} kontekstuelle instrukser`,
Edit: "Kontekstuelle -og minneinstrukser",
Add: "Legg til",
},
Exporter: {
Description: {
Title: "Bare meldinger etter at konteksten er ryddet vil bli vist",
},
Model: "Modell",
Messages: "Meldinger",
Model: "Model",
Messages: "Meldingar",
Topic: "Emne",
Time: "Tid",
},

View File

@@ -153,12 +153,6 @@ const pt: PartialLocaleType = {
Title: "Tamanho da Fonte",
SubTitle: "Ajustar o tamanho da fonte do conteúdo do chat",
},
FontFamily: {
Title: "Fonte do Chat",
SubTitle:
"Fonte do conteúdo do chat, deixe vazio para aplicar a fonte padrão global",
Placeholder: "Nome da Fonte",
},
InjectSystemPrompts: {
Title: "Inserir Prompts de Sistema",
SubTitle: "Inserir um prompt de sistema global para cada requisição",
@@ -405,21 +399,6 @@ const pt: PartialLocaleType = {
FineTuned: {
Sysmessage: "Você é um assistente que",
},
SearchChat: {
Name: "Pesquisar",
Page: {
Title: "Pesquisar histórico de chat",
Search: "Digite palavras-chave para pesquisa",
NoResult: "Nenhum resultado encontrado",
NoData: "Sem dados",
Loading: "Carregando",
SubTitle: (count: number) => `Encontrado ${count} resultados`,
},
Item: {
View: "Ver",
},
},
Mask: {
Name: "Máscara",
Page: {

View File

@@ -1,552 +1,229 @@
import { SubmitKey } from "../store/config";
import { PartialLocaleType } from "../locales/index";
import { getClientConfig } from "../config/client";
const isApp = !!getClientConfig()?.isApp;
import type { PartialLocaleType } from "./index";
const ru: PartialLocaleType = {
WIP: "Скоро...",
Error: {
Unauthorized: isApp
? "Обнаружен недействительный API-ключ. Пожалуйста, перейдите на страницу [Настройки](/#/settings), чтобы проверить правильность конфигурации API-ключа."
: "Неверный или пустой пароль доступа. Пожалуйста, перейдите на страницу [Вход](/#/auth), чтобы ввести правильный пароль доступа, или на страницу [Настройки](/#/settings), чтобы ввести ваш собственный API-ключ OpenAI.",
},
Auth: {
Title: "Требуется пароль",
Tips: "Администратор включил проверку пароля. Пожалуйста, введите код доступа ниже",
SubTips: "Или введите ваш API-ключ OpenAI или Google",
Input: "Введите код доступа здесь",
Confirm: "Подтвердить",
Later: "Позже",
Unauthorized:
"Несанкционированный доступ. Пожалуйста, введите код доступа на [странице](/#/auth) настроек.",
},
ChatItem: {
ChatItemCount: (count: number) => `${count} бесед`,
ChatItemCount: (count: number) => `${count} сообщений`,
},
Chat: {
SubTitle: (count: number) => `Всего ${count} бесед`,
EditMessage: {
Title: "Редактировать сообщение",
Topic: {
Title: "Тема чата",
SubTitle: "Изменить текущую тему чата",
},
},
SubTitle: (count: number) => `${count} сообщений с ChatGPT`,
Actions: {
ChatList: росмотреть список сообщений",
CompressedHistory: "Просмотреть сжатую историю подсказок",
Export: "Экспортировать чат",
ChatList: ерейти к списку чатов",
CompressedHistory: "Сжатая история памяти",
Export: "Экспортировать все сообщения в формате Markdown",
Copy: "Копировать",
Stop: "Остановить",
Retry: "Повторить",
Pin: "Закрепить",
PinToastContent: "1 беседа закреплена в предустановленных подсказках",
PinToastAction: "Просмотреть",
Delete: "Удалить",
Edit: "Редактировать",
},
Commands: {
new: "Новый чат",
newm: "Создать чат из маски",
next: "Следующий чат",
prev: "Предыдущий чат",
clear: "Очистить контекст",
del: "Удалить чат",
},
InputActions: {
Stop: "Остановить ответ",
ToBottom: "Перейти к последнему",
Theme: {
auto: "Автоматическая тема",
light: "Светлая тема",
dark: "Темная тема",
},
Prompt: "Быстрая команда",
Masks: "Все маски",
Clear: "Очистить чат",
Settings: "Настройки чата",
UploadImage: "Загрузить изображение",
},
Rename: "Переименовать чат",
Typing: "Печатает…",
Input: (submitKey: string) => {
var inputHints = `${submitKey} Отправить`;
var inputHints = `${submitKey} для отправки сообщения`;
if (submitKey === String(SubmitKey.Enter)) {
inputHints += "Shift + Enter для новой строки";
inputHints += ", Shift + Enter для переноса строки";
}
return inputHints + "/ для автозаполнения,: для команд";
return inputHints + ", / для поиска подсказок";
},
Send: "Отправить",
Config: {
Reset: "Очистить память",
Reset: "Сбросить настройки",
SaveAs: "Сохранить как маску",
},
IsContext: "Предустановленные подсказки",
},
Export: {
Title: "Поделиться историей чата",
Title: "Все сообщения",
Copy: "Копировать все",
Download: "Скачать файл",
Share: "Поделиться в ShareGPT",
MessageFromYou: "Пользователь",
MessageFromChatGPT: "ChatGPT",
Format: {
Title: "Формат экспорта",
SubTitle: "Можно экспортировать как Markdown текст или PNG изображение",
},
IncludeContext: {
Title: "Включить контекст маски",
SubTitle: "Показывать ли контекст маски в сообщениях",
},
Steps: {
Select: "Выбрать",
Preview: "Предпросмотр",
},
Image: {
Toast: "Создание скриншота",
Modal: "Длительное нажатие или правый клик для сохранения изображения",
},
},
Select: {
Search: "Поиск сообщений",
All: "Выбрать все",
Latest: "Последние сообщения",
Clear: "Очистить выбор",
Download: "Скачать",
MessageFromYou: "Сообщение от вас",
MessageFromChatGPT: "Сообщение от ChatGPT",
},
Memory: {
Title: "Историческое резюме",
EmptyContent: "Содержимое чата слишком короткое, чтобы суммировать",
Send: "Автоматически сжать историю чата и отправить как контекст",
Copy: "Копировать резюме",
Reset: "[не используется]",
ResetConfirm: "Подтвердить очистку исторического резюме?",
Title: "Память",
EmptyContent: "Пусто.",
Send: "Отправить память",
Copy: "Копировать память",
Reset: "Сбросить сессию",
ResetConfirm:
"При сбросе текущая история переписки и историческая память будут удалены. Вы уверены, что хотите сбросить?",
},
Home: {
NewChat: "Новый чат",
DeleteChat: "Подтвердить удаление выбранного чата?",
DeleteToast: "Беседа удалена",
Revert: "Отменить",
DeleteChat: "Вы действительно хотите удалить выбранный разговор?",
DeleteToast: "Чат удален",
Revert: "Отмена",
},
Settings: {
Title: "Настройки",
SubTitle: "Все параметры настроек",
SubTitle: "Все настройки",
Danger: {
Reset: {
Title: "Сброс всех настроек",
SubTitle: "Сброс всех параметров до значений по умолчанию",
Action: "Сбросить сейчас",
Confirm: "Подтвердить сброс всех настроек?",
},
Clear: {
Title: "Очистить все данные",
SubTitle: "Очистить все чаты и данные настроек",
Action: "Очистить сейчас",
Confirm: "Подтвердить очистку всех чатов и данных настроек?",
},
},
Lang: {
Name: "Language", // ATTENTION: если вы хотите добавить новый перевод, не переводите это значение, оставьте его как `Language`
Name: "Language", // ATTENTION: if you wanna add a new translation, please do not translate this value, leave it as `Language`
All: "Все языки",
},
Avatar: "Аватар",
FontSize: {
Title: "Размер шрифта",
SubTitle: "Размер шрифта в чате",
},
FontFamily: {
Title: "Шрифт чата",
SubTitle:
"Шрифт содержимого чата, оставьте пустым для применения глобального шрифта по умолчанию",
Placeholder: "Название шрифта",
SubTitle: "Настроить размер шрифта контента чата",
},
InjectSystemPrompts: {
Title: "Вставить системные подсказки",
SubTitle:
"Принудительно добавлять системную подсказку, имитирующую ChatGPT, в начале каждого запроса",
"Принудительно добавить симулированную системную подсказку ChatGPT в начало списка сообщений для каждого запроса",
},
InputTemplate: {
Title: "Предварительная обработка пользовательского ввода",
SubTitle:
"Последнее сообщение пользователя будет подставлено в этот шаблон",
},
Update: {
Version: (x: string) => `Текущая версия: ${x}`,
IsLatest: "Установлена последняя версия",
CheckUpdate: "Проверить обновления",
IsChecking: "Проверка обновлений...",
FoundUpdate: (x: string) => `Найдено новое обновление: ${x}`,
GoToUpdate: "Перейти к обновлению",
Version: (x: string) => `Версия: ${x}`,
IsLatest: "Последняя версия",
CheckUpdate: "Проверить обновление",
IsChecking: "Проверка обновления...",
FoundUpdate: (x: string) => `Найдена новая версия: ${x}`,
GoToUpdate: "Обновить",
},
SendKey: "Кнопка отправки",
SendKey: "Клавиша отправки",
Theme: "Тема",
TightBorder: "Режим без границ",
TightBorder: "Узкая граница",
SendPreviewBubble: {
Title: "Предварительный просмотр пузырьков",
SubTitle:
"Просмотр содержимого Markdown в пузырьках предварительного просмотра",
},
AutoGenerateTitle: {
Title: "Автоматическое создание заголовка",
SubTitle: "Создание подходящего заголовка на основе содержания беседы",
},
Sync: {
CloudState: "Облачные данные",
NotSyncYet: "Синхронизация еще не проводилась",
Success: "Синхронизация успешна",
Fail: "Не удалось синхронизировать",
Config: {
Modal: {
Title: "Настройки облачной синхронизации",
Check: "Проверить доступность",
},
SyncType: {
Title: "Тип синхронизации",
SubTitle: "Выберите предпочитаемый сервер синхронизации",
},
Proxy: {
Title: "Включить прокси",
SubTitle:
"При синхронизации в браузере необходимо включить прокси для предотвращения ограничений кросс-домена",
},
ProxyUrl: {
Title: "Адрес прокси",
SubTitle: "Только для встроенного прокси в проекте",
},
WebDav: {
Endpoint: "WebDAV адрес",
UserName: "Имя пользователя",
Password: "Пароль",
},
UpStash: {
Endpoint: "UpStash Redis REST Url",
UserName: "Имя резервной копии",
Password: "UpStash Redis REST Token",
},
},
LocalState: "Локальные данные",
Overview: (overview: any) => {
return `${overview.chat} бесед, ${overview.message} сообщений, ${overview.prompt} подсказок, ${overview.mask} масок`;
},
ImportFailed: "Не удалось импортировать",
Title: "Отправить предпросмотр",
SubTitle: "Предварительный просмотр markdown в пузыре",
},
Mask: {
Splash: {
Title: "Стартовая страница масок",
SubTitle:
"При создании нового чата отображать стартовую страницу масок",
},
Builtin: {
Title: "Скрыть встроенные маски",
SubTitle: "Скрыть встроенные маски во всех списках масок",
Title: "Экран заставки маски",
SubTitle: "Показывать экран заставки маски перед началом нового чата",
},
},
Prompt: {
Disable: {
Title: "Отключить автозаполнение подсказок",
SubTitle: "Введите / в начале строки для активации автозаполнения",
Title: "Отключить автозаполнение",
SubTitle: "Ввод / для запуска автозаполнения",
},
List: "Список пользовательских подсказок",
List: "Список подсказок",
ListCount: (builtin: number, custom: number) =>
`Встроенные ${builtin}, пользовательские ${custom}`,
`${builtin} встроенных, ${custom} пользовательских`,
Edit: "Редактировать",
Modal: {
Title: "Список подсказок",
Add: "Создать",
Add: "Добавить",
Search: "Поиск подсказок",
},
EditModal: {
Title: "Редактировать подсказки",
Title: "Редактировать подсказку",
},
},
HistoryCount: {
Title: "Количество истории сообщений",
SubTitle: "Количество историй сообщений, отправляемых с каждым запросом",
Title: "Количество прикрепляемых сообщений",
SubTitle:
"Количество отправляемых сообщений, прикрепляемых к каждому запросу",
},
CompressThreshold: {
Title: "Порог сжатия длины истории сообщений",
Title: "Порог сжатия истории",
SubTitle:
"Когда не сжатая история сообщений превышает это значение, происходит сжатие",
"Будет сжимать, если длина несжатых сообщений превышает указанное значение",
},
Usage: {
Title: "Проверка баланса",
Title: "Баланс аккаунта",
SubTitle(used: any, total: any) {
return `Использовано в этом месяце $${used}, всего по подписке $${total}`;
},
IsChecking: "Проверка…",
Check: "Проверить снова",
NoAccess: "Введите API-ключ или пароль доступа для просмотра баланса",
},
Access: {
AccessCode: {
Title: "Пароль доступа",
SubTitle: "Администратор включил защиту паролем",
Placeholder: "Введите пароль доступа",
},
CustomEndpoint: {
Title: "Пользовательский интерфейс",
SubTitle: "Использовать ли пользовательский Azure или OpenAI сервис",
},
Provider: {
Title: "Провайдер модели",
SubTitle: "Переключиться на другого провайдера",
},
OpenAI: {
ApiKey: {
Title: "API-ключ",
SubTitle:
"Использовать пользовательский OpenAI-ключ для обхода ограничений пароля",
Placeholder: "OpenAI API-ключ",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle: "Кроме адреса по умолчанию, должен содержать http(s)://",
},
},
Azure: {
ApiKey: {
Title: "Ключ интерфейса",
SubTitle:
"Использовать пользовательский Azure-ключ для обхода ограничений пароля",
Placeholder: "Azure API-ключ",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle: "Пример:",
},
ApiVerion: {
Title: "Версия интерфейса (azure api version)",
SubTitle: "Выберите конкретную версию",
},
},
Anthropic: {
ApiKey: {
Title: "Ключ интерфейса",
SubTitle:
"Использовать пользовательский Anthropic-ключ для обхода ограничений пароля",
Placeholder: "Anthropic API-ключ",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle: "Пример:",
},
ApiVerion: {
Title: "Версия интерфейса (claude api version)",
SubTitle: "Выберите конкретную версию API",
},
},
Google: {
ApiKey: {
Title: "API-ключ",
SubTitle: "Получите ваш API-ключ Google AI",
Placeholder: "Введите ваш API-ключ Google AI Studio",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle: "Пример:",
},
ApiVersion: {
Title: "Версия API (только для gemini-pro)",
SubTitle: "Выберите конкретную версию API",
},
GoogleSafetySettings: {
Title: "Уровень фильтрации Google",
SubTitle: "Настроить уровень фильтрации контента",
},
},
Baidu: {
ApiKey: {
Title: "API-ключ",
SubTitle: "Использовать пользовательский Baidu API-ключ",
Placeholder: "Baidu API-ключ",
},
SecretKey: {
Title: "Секретный ключ",
SubTitle: "Использовать пользовательский Baidu Secret Key",
Placeholder: "Baidu Secret Key",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle:
"Не поддерживает пользовательскую настройку, перейдите в .env",
},
},
ByteDance: {
ApiKey: {
Title: "Ключ интерфейса",
SubTitle: "Использовать пользовательский ByteDance API-ключ",
Placeholder: "ByteDance API-ключ",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle: "Пример:",
},
},
Alibaba: {
ApiKey: {
Title: "Ключ интерфейса",
SubTitle: "Использовать пользовательский Alibaba Cloud API-ключ",
Placeholder: "Alibaba Cloud API-ключ",
},
Endpoint: {
Title: "Адрес интерфейса",
SubTitle: "Пример:",
},
},
CustomModel: {
Title: "Название пользовательской модели",
SubTitle:
"Добавьте варианты пользовательских моделей, разделяя запятыми",
return `Использовано в этом месяце $${used}, подписка $${total}`;
},
IsChecking: "Проверка...",
Check: "Проверить",
NoAccess: "Введите API ключ, чтобы проверить баланс",
},
Model: "Модель",
Temperature: {
Title: "Случайность (temperature)",
SubTitle: "Чем больше значение, тем более случайные ответы",
},
TopP: {
Title: "Ядро выборки (top_p)",
SubTitle: "Похожие на случайность, но не изменяйте вместе с случайностью",
Title: "Температура",
SubTitle: "Чем выше значение, тем более случайный вывод",
},
MaxTokens: {
Title: "Ограничение на количество токенов за один раз (max_tokens)",
SubTitle: "Максимальное количество токенов на одно взаимодействие",
Title: "Максимальное количество токенов",
SubTitle: "Максимальная длина вводных и генерируемых токенов",
},
PresencePenalty: {
Title: "Наказание за новизну тем (presence_penalty)",
Title: "Штраф за повторения",
SubTitle:
"Чем больше значение, тем выше вероятность расширения на новые темы",
"Чем выше значение, тем больше вероятность общения на новые темы",
},
FrequencyPenalty: {
Title: "Наказание за частоту (frequency_penalty)",
Title: "Штраф за частоту",
SubTitle:
"Чем больше значение, тем выше вероятность уменьшения повторяющихся слов",
"Большее значение снижает вероятность повторения одной и той же строки",
},
},
Store: {
DefaultTopic: "Новый чат",
BotHello: "Чем могу помочь?",
Error: "Произошла ошибка, попробуйте позже",
DefaultTopic: "Новый разговор",
BotHello: "Здравствуйте! Как я могу вам помочь сегодня?",
Error: "Что-то пошло не так. Пожалуйста, попробуйте еще раз позже.",
Prompt: {
History: (content: string) =>
"Это резюме истории чата как предыстория: " + content,
"Это краткое содержание истории чата между ИИ и пользователем: " +
content,
Topic:
"Укажите краткую тему этого сообщения в четырех-пяти словах, без объяснений, знаков препинания, междометий, лишнего текста или выделения. Если темы нет, просто напишите 'Болтовня'",
"Пожалуйста, создайте заголовок из четырех или пяти слов, который кратко описывает нашу беседу, без введения, знаков пунктуации, кавычек, точек, символов или дополнительного текста. Удалите кавычки.",
Summarize:
"Кратко подведите итоги содержимого беседы для использования в качестве последующего контекстного запроса, не более 200 слов",
"Кратко изложите нашу дискуссию в 200 словах или менее для использования в будущем контексте.",
},
},
Copy: {
Success: "Скопировано в буфер обмена",
Failed: "Не удалось скопировать, предоставьте доступ к буферу обмена",
},
Download: {
Success: "Содержимое успешно загружено в вашу директорию.",
Failed: "Не удалось загрузить.",
Failed:
"Не удалось скопировать, пожалуйста, предоставьте разрешение на доступ к буферу обмена",
},
Context: {
Toast: (x: any) => `Содержит ${x} предустановленных подсказок`,
Edit: "Текущие настройки чата",
Add: "Добавить новый чат",
Clear: "Контекст очищен",
Revert: "Восстановить контекст",
Toast: (x: any) => `С ${x} контекстными подсказками`,
Edit: "Контекстные и памятные подсказки",
Add: "Добавить подсказку",
},
Plugin: {
Name: "Плагины",
Name: "Плагин",
},
FineTuned: {
Sysmessage: "Вы - помощник",
},
SearchChat: {
Name: "Поиск",
Page: {
Title: "Поиск в истории чатов",
Search: "Введите ключевые слова для поиска",
NoResult: "Результатов не найдено",
NoData: "Нет данных",
Loading: "Загрузка",
SubTitle: (count: number) => `Найдено ${count} результатов`,
},
Item: {
View: "Просмотр",
},
Sysmessage: "Вы - ассистент, который",
},
Mask: {
Name: "Маска",
Page: {
Title: "Предустановленные роли",
SubTitle: (count: number) => `${count} предустановленных ролей`,
Search: "Поиск ролей",
Title: "Шаблон подсказки",
SubTitle: (count: number) => `${count} шаблонов подсказок`,
Search: "Поиск шаблонов",
Create: "Создать",
},
Item: {
Info: (count: number) => `Содержит ${count} предустановленных диалогов`,
Chat: "Диалог",
View: "Просмотреть",
Info: (count: number) => `${count} подсказок`,
Chat: "Чат",
View: "Просмотр",
Edit: "Редактировать",
Delete: "Удалить",
DeleteConfirm: "Подтвердить удаление?",
},
EditModal: {
Title: (readonly: boolean) =>
`Редактирование предустановленной маски ${
readonly ? "только для чтения" : ""
`Редактирование шаблона подсказки ${
readonly ? "(только для чтения)" : ""
}`,
Download: "Скачать предустановку",
Clone: "Клонировать предустановку",
Download: "Скачать",
Clone: "Клонировать",
},
Config: {
Avatar: "Аватар роли",
Name: "Название роли",
Sync: {
Title: "Использовать глобальные настройки",
SubTitle:
"Будет ли текущий чат использовать глобальные настройки модели",
Confirm:
"Пользовательские настройки текущего чата будут автоматически заменены, подтвердите активацию глобальных настроек?",
},
HideContext: {
Title: "Скрыть предустановленные диалоги",
SubTitle:
"После скрытия предустановленные диалоги не будут отображаться в чате",
},
Share: {
Title: "Поделиться этой маской",
SubTitle: "Создать прямую ссылку на эту маску",
Action: "Скопировать ссылку",
},
Avatar: "Аватар бота",
Name: "Имя бота",
},
},
NewChat: {
Return: "Вернуться",
Skip: "Начать сразу",
NotShow: "Больше не показывать",
ConfirmNoShow:
"Подтвердить отключение? После отключения вы всегда сможете включить его снова в настройках.",
Skip: "Пропустить",
Title: "Выберите маску",
SubTitle: "Начните сейчас, столкнитесь с мыслями за маской",
More: "Показать все",
},
URLCommand: {
Code: "Обнаружен код доступа в ссылке, автоматически заполнить?",
Settings:
"Обнаружены предустановленные настройки в ссылке, автоматически заполнить?",
SubTitle: "Общайтесь с душой за маской",
More: "Найти еще",
NotShow: "Не показывать снова",
ConfirmNoShow:
"Подтвердите отключение? Вы можете включить это позже в настройках.",
},
UI: {
@@ -555,15 +232,8 @@ const ru: PartialLocaleType = {
Close: "Закрыть",
Create: "Создать",
Edit: "Редактировать",
Export: "Экспортировать",
Import: "Импортировать",
Sync: "Синхронизировать",
Config: "Настройки",
},
Exporter: {
Description: {
Title: "Только сообщения после очистки контекста будут отображаться",
},
Model: "Модель",
Messages: "Сообщения",
Topic: "Тема",

Some files were not shown because too many files have changed in this diff Show More