Compare commits

..

24 Commits

Author SHA1 Message Date
lloydzhou
aef119bb2b add plugins 2024-09-26 15:07:18 +08:00
lloydzhou
b2de4c0461 add updater 2024-09-26 14:42:23 +08:00
lloydzhou
540f93ad25 remove DEFAULT_API_HOST 2024-09-25 20:46:01 +08:00
lloydzhou
cc33b7b6bf using tauriFetch fro fetchEventSource 2024-09-25 20:29:20 +08:00
lloydzhou
7f857284bb update 2024-09-25 20:03:18 +08:00
lloydzhou
9bd1635064 using @tauri-apps/plugin-http replace @tauri-apps/api/http 2024-09-25 19:49:57 +08:00
lloydzhou
4c9fe56f33 using @tauri-apps/plugin-http replace @tauri-apps/api/http 2024-09-25 19:49:11 +08:00
lloydzhou
29296d42d7 using this version from github fixed data_directory for webkitgtk 2024-09-25 15:30:02 +08:00
lloydzhou
d306491e88 update 2024-09-25 13:16:37 +08:00
lloydzhou
a7d8abbc4d Merge remote-tracking branch 'origin/feat-tauir-v2' into feat-tauir-v2 2024-09-25 00:15:46 +08:00
lloydzhou
4c6a593ae3 hotfix for get version in action 2024-09-25 00:13:36 +08:00
Lloyd Zhou
9ba1b39cf5 Merge pull request #5518 from WtecHtec/main
support tauri-v2
2024-09-24 23:39:10 +08:00
river
454c247de6 chore: remove specta 2024-09-24 21:22:13 +08:00
river
cb6576ec04 feat: simple cargo 2024-09-24 21:19:45 +08:00
river
2758ea5ddd Merge branch 'main' of github.com:WtecHtec/ChatGPT-Next-Web into wtec-main 2024-09-24 21:03:15 +08:00
river
a2e9e78457 chore: update config 2024-09-24 21:03:10 +08:00
sr7
b720ba4c30 删除多余 2024-09-24 20:48:41 +08:00
sr7
7151c0134a 删除多余 2024-09-24 20:36:11 +08:00
sr7
97099849b7 删除多余 2024-09-24 20:29:49 +08:00
river
1fa58c60d9 chore: update config 2024-09-24 20:29:43 +08:00
river
5aaa190a7d chore: remove package-lock 2024-09-24 20:17:46 +08:00
sr7
b9e6dce193 support tauri-v2 2024-09-24 18:52:38 +08:00
sr7
7b1667f204 support tauri-v2 2024-09-24 18:40:24 +08:00
sr7
87c5b72ea2 support tauri-v2 2024-09-24 18:38:12 +08:00
73 changed files with 5766 additions and 7171 deletions

View File

@@ -20,7 +20,7 @@ jobs:
with: with:
node-version: 18 node-version: 18
- name: get version - name: get version
run: echo "PACKAGE_VERSION=$(node -p "require('./src-tauri/tauri.conf.json').package.version")" >> $GITHUB_ENV run: echo "PACKAGE_VERSION=$(node -p "require('./src-tauri/tauri.conf.json').version")" >> $GITHUB_ENV
- name: create release - name: create release
id: create-release id: create-release
uses: actions/github-script@v6 uses: actions/github-script@v6
@@ -69,7 +69,7 @@ jobs:
if: matrix.config.os == 'ubuntu-latest' if: matrix.config.os == 'ubuntu-latest'
run: | run: |
sudo apt-get update sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf sudo apt-get install -y libgtk-3-dev libsoup-3.0-dev libjavascriptcoregtk-4.1 libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: install frontend dependencies - name: install frontend dependencies
run: yarn install # change this to npm or pnpm depending on which one you use run: yarn install # change this to npm or pnpm depending on which one you use
- uses: tauri-apps/tauri-action@v0 - uses: tauri-apps/tauri-action@v0

1
.gitignore vendored
View File

@@ -46,3 +46,4 @@ dev
*.key.pub *.key.pub
masks.json masks.json
package-lock.json

View File

@@ -12,18 +12,15 @@ One-Click to get a well-designed cross-platform ChatGPT web UI, with GPT3, GPT4
一键免费部署你的跨平台私人 ChatGPT 应用, 支持 GPT3, GPT4 & Gemini Pro 模型。 一键免费部署你的跨平台私人 ChatGPT 应用, 支持 GPT3, GPT4 & Gemini Pro 模型。
[![Saas][Saas-image]][saas-url]
[![Web][Web-image]][web-url] [![Web][Web-image]][web-url]
[![Windows][Windows-image]][download-url] [![Windows][Windows-image]][download-url]
[![MacOS][MacOS-image]][download-url] [![MacOS][MacOS-image]][download-url]
[![Linux][Linux-image]][download-url] [![Linux][Linux-image]][download-url]
[NextChatAI](https://nextchat.dev/chat?utm_source=readme) / [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) / [Enterprise Edition](#enterprise-edition) / [Twitter](https://twitter.com/NextChatDev)
[NextChatAI](https://nextchat.dev/chat) / [网页版](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) / [企业版](#%E4%BC%81%E4%B8%9A%E7%89%88) / [反馈](https://github.com/Yidadaa/ChatGPT-Next-Web/issues)
[saas-url]: https://nextchat.dev/chat?utm_source=readme
[saas-image]: https://img.shields.io/badge/NextChat-Saas-green?logo=microsoftedge
[web-url]: https://app.nextchat.dev/ [web-url]: https://app.nextchat.dev/
[download-url]: https://github.com/Yidadaa/ChatGPT-Next-Web/releases [download-url]: https://github.com/Yidadaa/ChatGPT-Next-Web/releases
[Web-image]: https://img.shields.io/badge/Web-PWA-orange?logo=microsoftedge [Web-image]: https://img.shields.io/badge/Web-PWA-orange?logo=microsoftedge
@@ -63,7 +60,7 @@ For enterprise inquiries, please contact: **business@nextchat.dev**
企业版咨询: **business@nextchat.dev** 企业版咨询: **business@nextchat.dev**
<img width="300" src="https://github.com/user-attachments/assets/3d4305ac-6e95-489e-884b-51d51db5f692"> <img width="300" src="https://github.com/user-attachments/assets/3daeb7b6-ab63-4542-9141-2e4a12c80601">
## Features ## Features
@@ -100,7 +97,6 @@ For enterprise inquiries, please contact: **business@nextchat.dev**
## What's New ## What's New
- 🚀 v2.15.4 The Application supports using Tauri fetch LLM API, MORE SECURITY! [#5379](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5379)
- 🚀 v2.15.0 Now supports Plugins! Read this: [NextChat-Awesome-Plugins](https://github.com/ChatGPTNextWeb/NextChat-Awesome-Plugins) - 🚀 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.14.0 Now supports Artifacts & SD
- 🚀 v2.10.1 support Google Gemini Pro model. - 🚀 v2.10.1 support Google Gemini Pro model.
@@ -138,7 +134,6 @@ For enterprise inquiries, please contact: **business@nextchat.dev**
## 最新动态 ## 最新动态
- 🚀 v2.15.4 客户端支持Tauri本地直接调用大模型API更安全[#5379](https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/issues/5379)
- 🚀 v2.15.0 现在支持插件功能了!了解更多:[NextChat-Awesome-Plugins](https://github.com/ChatGPTNextWeb/NextChat-Awesome-Plugins) - 🚀 v2.15.0 现在支持插件功能了!了解更多:[NextChat-Awesome-Plugins](https://github.com/ChatGPTNextWeb/NextChat-Awesome-Plugins)
- 🚀 v2.14.0 现在支持 Artifacts & SD 了。 - 🚀 v2.14.0 现在支持 Artifacts & SD 了。
- 🚀 v2.10.1 现在支持 Gemini Pro 模型。 - 🚀 v2.10.1 现在支持 Gemini Pro 模型。
@@ -177,7 +172,7 @@ We recommend that you follow the steps below to re-deploy:
### Enable Automatic Updates ### Enable Automatic Updates
> If you encounter a failure of Upstream Sync execution, please [manually update code](./README.md#manually-updating-code). > If you encounter a failure of Upstream Sync execution, please manually sync fork once.
After forking the project, due to the limitations imposed by GitHub, you need to manually enable Workflows and Upstream Sync Action on the Actions page of the forked project. Once enabled, automatic updates will be scheduled every hour: After forking the project, due to the limitations imposed by GitHub, you need to manually enable Workflows and Upstream Sync Action on the Actions page of the forked project. Once enabled, automatic updates will be scheduled every hour:
@@ -334,9 +329,9 @@ 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. 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. 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. > 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. > 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. 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. > Example: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` will show option `Doubao-lite-4k(ByteDance)` in model list.

View File

@@ -8,7 +8,7 @@
一键免费部署你的私人 ChatGPT 网页应用,支持 GPT3, GPT4 & Gemini Pro 模型。 一键免费部署你的私人 ChatGPT 网页应用,支持 GPT3, GPT4 & Gemini Pro 模型。
[NextChatAI](https://nextchat.dev/chat?utm_source=readme) / [企业版](#%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) [企业版](#%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)
[<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) [<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)
@@ -54,7 +54,7 @@
### 打开自动更新 ### 打开自动更新
> 如果你遇到了 Upstream Sync 执行错误,请[手动 Sync Fork 一次](./README_CN.md#手动更新代码) > 如果你遇到了 Upstream Sync 执行错误,请手动 Sync Fork 一次!
当你 fork 项目之后,由于 Github 的限制,需要手动去你 fork 后的项目的 Actions 页面启用 Workflows并启用 Upstream Sync Action启用之后即可开启每小时定时自动更新 当你 fork 项目之后,由于 Github 的限制,需要手动去你 fork 后的项目的 Actions 页面启用 Workflows并启用 Upstream Sync Action启用之后即可开启每小时定时自动更新
@@ -216,9 +216,9 @@ ByteDance Api Url.
用来控制模型列表,使用 `+` 增加一个模型,使用 `-` 来隐藏一个模型,使用 `模型名=展示名` 来自定义模型的展示名,用英文逗号隔开。 用来控制模型列表,使用 `+` 增加一个模型,使用 `-` 来隐藏一个模型,使用 `模型名=展示名` 来自定义模型的展示名,用英文逗号隔开。
在Azure的模式下支持使用`modelName@Azure=deploymentName`的方式配置模型名称和部署名称(deploy-name) 在Azure的模式下支持使用`modelName@azure=deploymentName`的方式配置模型名称和部署名称(deploy-name)
> 示例:`+gpt-3.5-turbo@Azure=gpt35`这个配置会在模型列表显示一个`gpt35(Azure)`的选项。 > 示例:`+gpt-3.5-turbo@azure=gpt35`这个配置会在模型列表显示一个`gpt35(Azure)`的选项。
> 如果你只能使用Azure模式那么设置 `-all,+gpt-3.5-turbo@Azure=gpt35` 则可以让对话的默认使用 `gpt35(Azure)` > 如果你只能使用Azure模式那么设置 `-all,+gpt-3.5-turbo@azure=gpt35` 则可以让对话的默认使用 `gpt35(Azure)`
在ByteDance的模式下支持使用`modelName@bytedance=deploymentName`的方式配置模型名称和部署名称(deploy-name) 在ByteDance的模式下支持使用`modelName@bytedance=deploymentName`的方式配置模型名称和部署名称(deploy-name)
> 示例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx`这个配置会在模型列表显示一个`Doubao-lite-4k(ByteDance)`的选项 > 示例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx`这个配置会在模型列表显示一个`Doubao-lite-4k(ByteDance)`的选项

View File

@@ -5,7 +5,7 @@
ワンクリックで無料であなた専用の ChatGPT ウェブアプリをデプロイ。GPT3、GPT4 & Gemini Pro モデルをサポート。 ワンクリックで無料であなた専用の ChatGPT ウェブアプリをデプロイ。GPT3、GPT4 & Gemini Pro モデルをサポート。
[NextChatAI](https://nextchat.dev/chat?utm_source=readme) / [企業版](#企業版) / [デモ](https://chat-gpt-next-web.vercel.app/) / [フィードバック](https://github.com/Yidadaa/ChatGPT-Next-Web/issues) / [Discordに参加](https://discord.gg/zrhvHCr79N) [企業版](#企業版) / [デモ](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) [<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)
@@ -54,7 +54,7 @@
### 自動更新を開く ### 自動更新を開く
> Upstream Sync の実行エラーが発生した場合は、[手動で Sync Fork](./README_JA.md#手動でコードを更新する) してください! > Upstream Sync の実行エラーが発生した場合は、手動で Sync Fork してください!
プロジェクトを fork した後、GitHub の制限により、fork 後のプロジェクトの Actions ページで Workflows を手動で有効にし、Upstream Sync Action を有効にする必要があります。有効化後、毎時の定期自動更新が可能になります: プロジェクトを fork した後、GitHub の制限により、fork 後のプロジェクトの Actions ページで Workflows を手動で有効にし、Upstream Sync Action を有効にする必要があります。有効化後、毎時の定期自動更新が可能になります:
@@ -207,8 +207,8 @@ ByteDance API の URL。
モデルリストを管理します。`+` でモデルを追加し、`-` でモデルを非表示にし、`モデル名=表示名` でモデルの表示名をカスタマイズし、カンマで区切ります。 モデルリストを管理します。`+` でモデルを追加し、`-` でモデルを非表示にし、`モデル名=表示名` でモデルの表示名をカスタマイズし、カンマで区切ります。
Azure モードでは、`modelName@Azure=deploymentName` 形式でモデル名とデプロイ名deploy-nameを設定できます。 Azure モードでは、`modelName@azure=deploymentName` 形式でモデル名とデプロイ名deploy-nameを設定できます。
> 例:`+gpt-3.5-turbo@Azure=gpt35` この設定でモデルリストに `gpt35(Azure)` のオプションが表示されます。 > 例:`+gpt-3.5-turbo@azure=gpt35` この設定でモデルリストに `gpt35(Azure)` のオプションが表示されます。
ByteDance モードでは、`modelName@bytedance=deploymentName` 形式でモデル名とデプロイ名deploy-nameを設定できます。 ByteDance モードでは、`modelName@bytedance=deploymentName` 形式でモデル名とデプロイ名deploy-nameを設定できます。
> 例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` この設定でモデルリストに `Doubao-lite-4k(ByteDance)` のオプションが表示されます。 > 例: `+Doubao-lite-4k@bytedance=ep-xxxxx-xxx` この設定でモデルリストに `Doubao-lite-4k(ByteDance)` のオプションが表示されます。

View File

@@ -23,8 +23,7 @@ export async function handle(
}); });
} }
const bearToken = const bearToken = req.headers.get("Authorization") ?? "";
req.headers.get("x-goog-api-key") || req.headers.get("Authorization") || "";
const token = bearToken.trim().replaceAll("Bearer ", "").trim(); const token = bearToken.trim().replaceAll("Bearer ", "").trim();
const apiKey = token ? token : serverConfig.googleApiKey; const apiKey = token ? token : serverConfig.googleApiKey;
@@ -92,8 +91,8 @@ async function request(req: NextRequest, apiKey: string) {
}, },
10 * 60 * 1000, 10 * 60 * 1000,
); );
const fetchUrl = `${baseUrl}${path}${ const fetchUrl = `${baseUrl}${path}?key=${apiKey}${
req?.nextUrl?.searchParams?.get("alt") === "sse" ? "?alt=sse" : "" req?.nextUrl?.searchParams?.get("alt") === "sse" ? "&alt=sse" : ""
}`; }`;
console.log("[Fetch Url] ", fetchUrl); console.log("[Fetch Url] ", fetchUrl);
@@ -101,9 +100,6 @@ async function request(req: NextRequest, apiKey: string) {
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
"Cache-Control": "no-store", "Cache-Control": "no-store",
"x-goog-api-key":
req.headers.get("x-goog-api-key") ||
(req.headers.get("Authorization") ?? "").replace("Bearer ", ""),
}, },
method: req.method, method: req.method,
body: req.body, body: req.body,

View File

@@ -6,7 +6,7 @@ import { NextRequest, NextResponse } from "next/server";
import { auth } from "./auth"; import { auth } from "./auth";
import { requestOpenai } from "./common"; import { requestOpenai } from "./common";
const ALLOWED_PATH = new Set(Object.values(OpenaiPath)); const ALLOWD_PATH = new Set(Object.values(OpenaiPath));
function getModels(remoteModelRes: OpenAIListModelResponse) { function getModels(remoteModelRes: OpenAIListModelResponse) {
const config = getServerSideConfig(); const config = getServerSideConfig();
@@ -34,7 +34,7 @@ export async function handle(
const subpath = params.path.join("/"); const subpath = params.path.join("/");
if (!ALLOWED_PATH.has(subpath)) { if (!ALLOWD_PATH.has(subpath)) {
console.log("[OpenAI Route] forbidden path ", subpath); console.log("[OpenAI Route] forbidden path ", subpath);
return NextResponse.json( return NextResponse.json(
{ {

View File

@@ -231,7 +231,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
function getConfig() { function getConfig() {
const modelConfig = chatStore.currentSession().mask.modelConfig; const modelConfig = chatStore.currentSession().mask.modelConfig;
const isGoogle = modelConfig.providerName === ServiceProvider.Google; const isGoogle = modelConfig.providerName == ServiceProvider.Google;
const isAzure = modelConfig.providerName === ServiceProvider.Azure; const isAzure = modelConfig.providerName === ServiceProvider.Azure;
const isAnthropic = modelConfig.providerName === ServiceProvider.Anthropic; const isAnthropic = modelConfig.providerName === ServiceProvider.Anthropic;
const isBaidu = modelConfig.providerName == ServiceProvider.Baidu; const isBaidu = modelConfig.providerName == ServiceProvider.Baidu;
@@ -272,13 +272,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
} }
function getAuthHeader(): string { function getAuthHeader(): string {
return isAzure return isAzure ? "api-key" : isAnthropic ? "x-api-key" : "Authorization";
? "api-key"
: isAnthropic
? "x-api-key"
: isGoogle
? "x-goog-api-key"
: "Authorization";
} }
const { const {
@@ -289,15 +283,14 @@ export function getHeaders(ignoreHeaders: boolean = false) {
apiKey, apiKey,
isEnabledAccessControl, isEnabledAccessControl,
} = getConfig(); } = 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 // when using baidu api in app, not set auth header
if (isBaidu && clientConfig?.isApp) return headers; if (isBaidu && clientConfig?.isApp) return headers;
const authHeader = getAuthHeader(); const authHeader = getAuthHeader();
const bearerToken = getBearerToken( const bearerToken = getBearerToken(apiKey, isAzure || isAnthropic);
apiKey,
isAzure || isAnthropic || isGoogle,
);
if (bearerToken) { if (bearerToken) {
headers[authHeader] = bearerToken; headers[authHeader] = bearerToken;

View File

@@ -22,8 +22,7 @@ import {
} from "@fortaine/fetch-event-source"; } from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format"; import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client"; import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils"; import { getMessageTextContent, fetch } from "@/app/utils";
import { fetch } from "@/app/utils/stream";
export interface OpenAIListModelResponse { export interface OpenAIListModelResponse {
object: string; object: string;

View File

@@ -7,8 +7,6 @@ import {
usePluginStore, usePluginStore,
ChatMessageTool, ChatMessageTool,
} from "@/app/store"; } from "@/app/store";
import { getClientConfig } from "@/app/config/client";
import { ANTHROPIC_BASE_URL } from "@/app/constant";
import { getMessageTextContent, isVisionModel } from "@/app/utils"; import { getMessageTextContent, isVisionModel } from "@/app/utils";
import { preProcessImageContent, stream } from "@/app/utils/chat"; import { preProcessImageContent, stream } from "@/app/utils/chat";
import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare"; import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
@@ -386,9 +384,7 @@ export class ClaudeApi implements LLMApi {
// if endpoint is empty, use default endpoint // if endpoint is empty, use default endpoint
if (baseUrl.trim().length === 0) { if (baseUrl.trim().length === 0) {
const isApp = !!getClientConfig()?.isApp; baseUrl = ApiPath.Anthropic;
baseUrl = isApp ? ANTHROPIC_BASE_URL : ApiPath.Anthropic;
} }
if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) { if (!baseUrl.startsWith("http") && !baseUrl.startsWith("/api")) {

View File

@@ -23,8 +23,7 @@ import {
} from "@fortaine/fetch-event-source"; } from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format"; import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client"; import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils"; import { getMessageTextContent, fetch } from "@/app/utils";
import { fetch } from "@/app/utils/stream";
export interface OpenAIListModelResponse { export interface OpenAIListModelResponse {
object: string; object: string;

View File

@@ -22,8 +22,7 @@ import {
} from "@fortaine/fetch-event-source"; } from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format"; import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client"; import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils"; import { getMessageTextContent, fetch } from "@/app/utils";
import { fetch } from "@/app/utils/stream";
export interface OpenAIListModelResponse { export interface OpenAIListModelResponse {
object: string; object: string;

View File

@@ -7,26 +7,20 @@ import {
LLMUsage, LLMUsage,
SpeechOptions, SpeechOptions,
} from "../api"; } from "../api";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import Locale from "../../locales";
import { import {
useAccessStore, EventStreamContentType,
useAppConfig, fetchEventSource,
useChatStore, } from "@fortaine/fetch-event-source";
usePluginStore, import { prettyObject } from "@/app/utils/format";
ChatMessageTool,
} from "@/app/store";
import { stream } from "@/app/utils/chat";
import { getClientConfig } from "@/app/config/client";
import { GEMINI_BASE_URL } from "@/app/constant";
import { import {
getMessageTextContent, getMessageTextContent,
getMessageImages, getMessageImages,
isVisionModel, isVisionModel,
fetch,
} from "@/app/utils"; } from "@/app/utils";
import { preProcessImageContent } from "@/app/utils/chat"; import { preProcessImageContent } from "@/app/utils/chat";
import { nanoid } from "nanoid";
import { RequestPayload } from "./openai";
import { fetch } from "@/app/utils/stream";
export class GeminiProApi implements LLMApi { export class GeminiProApi implements LLMApi {
path(path: string): string { path(path: string): string {
@@ -37,9 +31,8 @@ export class GeminiProApi implements LLMApi {
baseUrl = accessStore.googleUrl; baseUrl = accessStore.googleUrl;
} }
const isApp = !!getClientConfig()?.isApp;
if (baseUrl.length === 0) { if (baseUrl.length === 0) {
baseUrl = isApp ? GEMINI_BASE_URL : ApiPath.Google; baseUrl = ApiPath.Google;
} }
if (baseUrl.endsWith("/")) { if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1); baseUrl = baseUrl.slice(0, baseUrl.length - 1);
@@ -53,6 +46,10 @@ export class GeminiProApi implements LLMApi {
let chatPath = [baseUrl, path].join("/"); let chatPath = [baseUrl, path].join("/");
chatPath += chatPath.includes("?") ? "&alt=sse" : "?alt=sse"; 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; return chatPath;
} }
extractMessage(res: any) { extractMessage(res: any) {
@@ -182,81 +179,115 @@ export class GeminiProApi implements LLMApi {
); );
if (shouldStream) { if (shouldStream) {
const [tools, funcs] = usePluginStore let responseText = "";
.getState() let remainText = "";
.getAsTools( let finished = false;
useChatStore.getState().currentSession().mask?.plugin || [],
);
return stream(
chatPath,
requestPayload,
getHeaders(),
// @ts-ignore
[{ functionDeclarations: tools.map((tool) => tool.function) }],
funcs,
controller,
// parseSSE
(text: string, runTools: ChatMessageTool[]) => {
// console.log("parseSSE", text, runTools);
const chunkJson = JSON.parse(text);
const functionCall = chunkJson?.candidates const finish = () => {
?.at(0) if (!finished) {
?.content.parts.at(0)?.functionCall; finished = true;
if (functionCall) { options.onFinish(responseText + remainText);
const { name, args } = functionCall; }
runTools.push({ };
id: nanoid(),
type: "function", // animate response to make it looks smooth
function: { function animateResponseText() {
name, if (finished || controller.signal.aborted) {
arguments: JSON.stringify(args), // utils.chat call function, using JSON.parse responseText += remainText;
}, finish();
}); return;
} }
return chunkJson?.candidates?.at(0)?.content.parts.at(0)?.text;
}, if (remainText.length > 0) {
// processToolMessage, include tool_calls message and tool call results const fetchCount = Math.max(1, Math.round(remainText.length / 60));
( const fetchText = remainText.slice(0, fetchCount);
requestPayload: RequestPayload, responseText += fetchText;
toolCallMessage: any, remainText = remainText.slice(fetchCount);
toolCallResult: any[], options.onUpdate?.(responseText, fetchText);
) => { }
// @ts-ignore
requestPayload?.contents?.splice( requestAnimationFrame(animateResponseText);
// @ts-ignore }
requestPayload?.contents?.length,
0, // start animaion
{ animateResponseText();
role: "model",
parts: toolCallMessage.tool_calls.map( controller.signal.onabort = finish;
(tool: ChatMessageTool) => ({
functionCall: { fetchEventSource(chatPath, {
name: tool?.function?.name, fetch: fetch as any,
args: JSON.parse(tool?.function?.arguments as string), ...chatPayload,
}, async onopen(res) {
}), clearTimeout(requestTimeoutId);
), const contentType = res.headers.get("content-type");
}, console.log(
// @ts-ignore "[Gemini] request response content type: ",
...toolCallResult.map((result) => ({ contentType,
role: "function",
parts: [
{
functionResponse: {
name: result.name,
response: {
name: result.name,
content: result.content, // TODO just text content...
},
},
},
],
})),
); );
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();
}
}, },
options, 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,
});
} else { } else {
const res = await fetch(chatPath, chatPayload); const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId); clearTimeout(requestTimeoutId);

View File

@@ -1,10 +1,5 @@
"use client"; "use client";
import { import { ApiPath, Iflytek, REQUEST_TIMEOUT_MS } from "@/app/constant";
ApiPath,
IFLYTEK_BASE_URL,
Iflytek,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store"; import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { import {
@@ -20,9 +15,7 @@ import {
fetchEventSource, fetchEventSource,
} from "@fortaine/fetch-event-source"; } from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format"; import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client"; import { getMessageTextContent, fetch } from "@/app/utils";
import { getMessageTextContent } from "@/app/utils";
import { fetch } from "@/app/utils/stream";
import { RequestPayload } from "./openai"; import { RequestPayload } from "./openai";
@@ -39,9 +32,7 @@ export class SparkApi implements LLMApi {
} }
if (baseUrl.length === 0) { if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp; baseUrl = ApiPath.Iflytek;
const apiPath = ApiPath.Iflytek;
baseUrl = isApp ? IFLYTEK_BASE_URL : apiPath;
} }
if (baseUrl.endsWith("/")) { if (baseUrl.endsWith("/")) {

View File

@@ -1,11 +1,6 @@
"use client"; "use client";
// azure and openai, using same models. so using same LLMApi. // azure and openai, using same models. so using same LLMApi.
import { import { ApiPath, Moonshot, REQUEST_TIMEOUT_MS } from "@/app/constant";
ApiPath,
MOONSHOT_BASE_URL,
Moonshot,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
import { import {
useAccessStore, useAccessStore,
useAppConfig, useAppConfig,
@@ -21,7 +16,6 @@ import {
LLMModel, LLMModel,
SpeechOptions, SpeechOptions,
} from "../api"; } from "../api";
import { getClientConfig } from "@/app/config/client";
import { getMessageTextContent } from "@/app/utils"; import { getMessageTextContent } from "@/app/utils";
import { RequestPayload } from "./openai"; import { RequestPayload } from "./openai";
@@ -38,9 +32,8 @@ export class MoonshotApi implements LLMApi {
} }
if (baseUrl.length === 0) { if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
const apiPath = ApiPath.Moonshot; const apiPath = ApiPath.Moonshot;
baseUrl = isApp ? MOONSHOT_BASE_URL : apiPath; baseUrl = apiPath;
} }
if (baseUrl.endsWith("/")) { if (baseUrl.endsWith("/")) {

View File

@@ -2,7 +2,6 @@
// azure and openai, using same models. so using same LLMApi. // azure and openai, using same models. so using same LLMApi.
import { import {
ApiPath, ApiPath,
OPENAI_BASE_URL,
DEFAULT_MODELS, DEFAULT_MODELS,
OpenaiPath, OpenaiPath,
Azure, Azure,
@@ -36,7 +35,6 @@ import {
SpeechOptions, SpeechOptions,
} from "../api"; } from "../api";
import Locale from "../../locales"; import Locale from "../../locales";
import { getClientConfig } from "@/app/config/client";
import { import {
getMessageTextContent, getMessageTextContent,
isVisionModel, isVisionModel,
@@ -63,7 +61,7 @@ export interface RequestPayload {
presence_penalty: number; presence_penalty: number;
frequency_penalty: number; frequency_penalty: number;
top_p: number; top_p: number;
max_completions_tokens?: number; max_tokens?: number;
} }
export interface DalleRequestPayload { export interface DalleRequestPayload {
@@ -96,9 +94,7 @@ export class ChatGPTApi implements LLMApi {
} }
if (baseUrl.length === 0) { if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp; baseUrl = isAzure ? ApiPath.Azure : ApiPath.OpenAI;
const apiPath = isAzure ? ApiPath.Azure : ApiPath.OpenAI;
baseUrl = isApp ? OPENAI_BASE_URL : apiPath;
} }
if (baseUrl.endsWith("/")) { if (baseUrl.endsWith("/")) {
@@ -228,16 +224,13 @@ export class ChatGPTApi implements LLMApi {
presence_penalty: !isO1 ? modelConfig.presence_penalty : 0, presence_penalty: !isO1 ? modelConfig.presence_penalty : 0,
frequency_penalty: !isO1 ? modelConfig.frequency_penalty : 0, frequency_penalty: !isO1 ? modelConfig.frequency_penalty : 0,
top_p: !isO1 ? modelConfig.top_p : 1, top_p: !isO1 ? modelConfig.top_p : 1,
// max_completions_tokens: Math.max(modelConfig.max_completions_tokens, 1024), // max_tokens: Math.max(modelConfig.max_tokens, 1024),
// Please do not ask me why not send max_completions_tokens, no reason, this param is just shit, I dont want to explain anymore. // 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_completions_tokens to vision model // add max_tokens to vision model
if (visionModel) { if (visionModel) {
requestPayload["max_completions_tokens"] = Math.max( requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
modelConfig.max_completions_tokens,
4000,
);
} }
} }

View File

@@ -1,5 +1,5 @@
"use client"; "use client";
import { ApiPath, TENCENT_BASE_URL, REQUEST_TIMEOUT_MS } from "@/app/constant"; import { ApiPath, REQUEST_TIMEOUT_MS } from "@/app/constant";
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store"; import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { import {
@@ -16,13 +16,11 @@ import {
fetchEventSource, fetchEventSource,
} from "@fortaine/fetch-event-source"; } from "@fortaine/fetch-event-source";
import { prettyObject } from "@/app/utils/format"; import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client"; import { getMessageTextContent, isVisionModel, fetch } from "@/app/utils";
import { getMessageTextContent, isVisionModel } from "@/app/utils";
import mapKeys from "lodash-es/mapKeys"; import mapKeys from "lodash-es/mapKeys";
import mapValues from "lodash-es/mapValues"; import mapValues from "lodash-es/mapValues";
import isArray from "lodash-es/isArray"; import isArray from "lodash-es/isArray";
import isObject from "lodash-es/isObject"; import isObject from "lodash-es/isObject";
import { fetch } from "@/app/utils/stream";
export interface OpenAIListModelResponse { export interface OpenAIListModelResponse {
object: string; object: string;
@@ -70,8 +68,7 @@ export class HunyuanApi implements LLMApi {
} }
if (baseUrl.length === 0) { if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp; baseUrl = ApiPath.Tencent;
baseUrl = isApp ? TENCENT_BASE_URL : ApiPath.Tencent;
} }
if (baseUrl.endsWith("/")) { if (baseUrl.endsWith("/")) {

View File

@@ -1,70 +1,12 @@
.auth-page { .auth-page {
display: flex; display: flex;
justify-content: flex-start; justify-content: center;
align-items: center; align-items: center;
height: 100%; height: 100%;
width: 100%; width: 100%;
flex-direction: column; flex-direction: column;
.top-banner {
position: relative;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
padding: 12px 64px;
box-sizing: border-box;
background: var(--second);
.top-banner-inner {
display: flex;
justify-content: center;
align-items: center;
font-size: 14px;
line-height: 150%;
span {
gap: 8px;
a {
display: inline-flex;
align-items: center;
text-decoration: none;
margin-left: 8px;
color: var(--primary);
}
}
}
.top-banner-close {
cursor: pointer;
position: absolute;
top: 50%;
right: 48px;
transform: translateY(-50%);
}
}
@media (max-width: 600px) {
.top-banner {
padding: 12px 24px 12px 12px;
.top-banner-close {
right: 10px;
}
.top-banner-inner {
.top-banner-logo {
margin-right: 8px;
}
}
}
}
.auth-header {
display: flex;
justify-content: space-between;
width: 100%;
padding: 10px;
box-sizing: border-box;
animation: slide-in-from-top ease 0.3s;
}
.auth-logo { .auth-logo {
margin-top: 10vh;
transform: scale(1.4); transform: scale(1.4);
} }
@@ -72,7 +14,6 @@
font-size: 24px; font-size: 24px;
font-weight: bold; font-weight: bold;
line-height: 2; line-height: 2;
margin-bottom: 1vh;
} }
.auth-tips { .auth-tips {
@@ -83,10 +24,6 @@
margin: 3vh 0; margin: 3vh 0;
} }
.auth-input-second {
margin: 0 0 3vh 0;
}
.auth-actions { .auth-actions {
display: flex; display: flex;
justify-content: center; justify-content: center;

View File

@@ -1,35 +1,21 @@
import styles from "./auth.module.scss"; import styles from "./auth.module.scss";
import { IconButton } from "./button"; import { IconButton } from "./button";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { Path, SAAS_CHAT_URL } from "../constant"; import { Path } from "../constant";
import { useAccessStore } from "../store"; import { useAccessStore } from "../store";
import Locale from "../locales"; import Locale from "../locales";
import Delete from "../icons/close.svg";
import Arrow from "../icons/arrow.svg";
import Logo from "../icons/logo.svg";
import { useMobileScreen } from "@/app/utils";
import BotIcon from "../icons/bot.svg"; import BotIcon from "../icons/bot.svg";
import { useEffect } from "react";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { PasswordInput } from "./ui-lib";
import LeftIcon from "@/app/icons/left.svg";
import { safeLocalStorage } from "@/app/utils";
import {
trackSettingsPageGuideToCPaymentClick,
trackAuthorizationPageButtonToCPaymentClick,
} from "../utils/auth-settings-events";
const storage = safeLocalStorage();
export function AuthPage() { export function AuthPage() {
const navigate = useNavigate(); const navigate = useNavigate();
const accessStore = useAccessStore(); const accessStore = useAccessStore();
const goHome = () => navigate(Path.Home); const goHome = () => navigate(Path.Home);
const goChat = () => navigate(Path.Chat); const goChat = () => navigate(Path.Chat);
const goSaas = () => {
trackAuthorizationPageButtonToCPaymentClick();
window.location.href = SAAS_CHAT_URL;
};
const resetAccessCode = () => { const resetAccessCode = () => {
accessStore.update((access) => { accessStore.update((access) => {
access.openaiApiKey = ""; access.openaiApiKey = "";
@@ -46,14 +32,6 @@ export function AuthPage() {
return ( return (
<div className={styles["auth-page"]}> <div className={styles["auth-page"]}>
<TopBanner></TopBanner>
<div className={styles["auth-header"]}>
<IconButton
icon={<LeftIcon />}
text={Locale.Auth.Return}
onClick={() => navigate(Path.Home)}
></IconButton>
</div>
<div className={`no-dark ${styles["auth-logo"]}`}> <div className={`no-dark ${styles["auth-logo"]}`}>
<BotIcon /> <BotIcon />
</div> </div>
@@ -61,43 +39,36 @@ export function AuthPage() {
<div className={styles["auth-title"]}>{Locale.Auth.Title}</div> <div className={styles["auth-title"]}>{Locale.Auth.Title}</div>
<div className={styles["auth-tips"]}>{Locale.Auth.Tips}</div> <div className={styles["auth-tips"]}>{Locale.Auth.Tips}</div>
<PasswordInput <input
style={{ marginTop: "3vh", marginBottom: "3vh" }} className={styles["auth-input"]}
aria={Locale.Settings.ShowPassword} type="password"
aria-label={Locale.Auth.Input}
value={accessStore.accessCode}
type="text"
placeholder={Locale.Auth.Input} placeholder={Locale.Auth.Input}
value={accessStore.accessCode}
onChange={(e) => { onChange={(e) => {
accessStore.update( accessStore.update(
(access) => (access.accessCode = e.currentTarget.value), (access) => (access.accessCode = e.currentTarget.value),
); );
}} }}
/> />
{!accessStore.hideUserApiKey ? ( {!accessStore.hideUserApiKey ? (
<> <>
<div className={styles["auth-tips"]}>{Locale.Auth.SubTips}</div> <div className={styles["auth-tips"]}>{Locale.Auth.SubTips}</div>
<PasswordInput <input
style={{ marginTop: "3vh", marginBottom: "3vh" }} className={styles["auth-input"]}
aria={Locale.Settings.ShowPassword} type="password"
aria-label={Locale.Settings.Access.OpenAI.ApiKey.Placeholder}
value={accessStore.openaiApiKey}
type="text"
placeholder={Locale.Settings.Access.OpenAI.ApiKey.Placeholder} placeholder={Locale.Settings.Access.OpenAI.ApiKey.Placeholder}
value={accessStore.openaiApiKey}
onChange={(e) => { onChange={(e) => {
accessStore.update( accessStore.update(
(access) => (access.openaiApiKey = e.currentTarget.value), (access) => (access.openaiApiKey = e.currentTarget.value),
); );
}} }}
/> />
<PasswordInput <input
style={{ marginTop: "3vh", marginBottom: "3vh" }} className={styles["auth-input"]}
aria={Locale.Settings.ShowPassword} type="password"
aria-label={Locale.Settings.Access.Google.ApiKey.Placeholder}
value={accessStore.googleApiKey}
type="text"
placeholder={Locale.Settings.Access.Google.ApiKey.Placeholder} placeholder={Locale.Settings.Access.Google.ApiKey.Placeholder}
value={accessStore.googleApiKey}
onChange={(e) => { onChange={(e) => {
accessStore.update( accessStore.update(
(access) => (access.googleApiKey = e.currentTarget.value), (access) => (access.googleApiKey = e.currentTarget.value),
@@ -114,74 +85,13 @@ export function AuthPage() {
onClick={goChat} onClick={goChat}
/> />
<IconButton <IconButton
text={Locale.Auth.SaasTips} text={Locale.Auth.Later}
onClick={() => { onClick={() => {
goSaas(); resetAccessCode();
goHome();
}} }}
/> />
</div> </div>
</div> </div>
); );
} }
function TopBanner() {
const [isHovered, setIsHovered] = useState(false);
const [isVisible, setIsVisible] = useState(true);
const isMobile = useMobileScreen();
useEffect(() => {
// 检查 localStorage 中是否有标记
const bannerDismissed = storage.getItem("bannerDismissed");
// 如果标记不存在,存储默认值并显示横幅
if (!bannerDismissed) {
storage.setItem("bannerDismissed", "false");
setIsVisible(true); // 显示横幅
} else if (bannerDismissed === "true") {
// 如果标记为 "true",则隐藏横幅
setIsVisible(false);
}
}, []);
const handleMouseEnter = () => {
setIsHovered(true);
};
const handleMouseLeave = () => {
setIsHovered(false);
};
const handleClose = () => {
setIsVisible(false);
storage.setItem("bannerDismissed", "true");
};
if (!isVisible) {
return null;
}
return (
<div
className={styles["top-banner"]}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<div className={`${styles["top-banner-inner"]} no-dark`}>
<Logo className={styles["top-banner-logo"]}></Logo>
<span>
{Locale.Auth.TopTips}
<a
href={SAAS_CHAT_URL}
rel="stylesheet"
onClick={() => {
trackSettingsPageGuideToCPaymentClick();
}}
>
{Locale.Settings.Access.SaasStart.ChatNow}
<Arrow style={{ marginLeft: "4px" }} />
</a>
</span>
</div>
{(isHovered || isMobile) && (
<Delete className={styles["top-banner-close"]} onClick={handleClose} />
)}
</div>
);
}

View File

@@ -5,6 +5,7 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
padding: 10px; padding: 10px;
cursor: pointer; cursor: pointer;
transition: all 0.3s ease; transition: all 0.3s ease;
overflow: hidden; overflow: hidden;

View File

@@ -1815,7 +1815,6 @@ function _Chat() {
{message?.tools?.map((tool) => ( {message?.tools?.map((tool) => (
<div <div
key={tool.id} key={tool.id}
title={tool?.errorMsg}
className={styles["chat-message-tool"]} className={styles["chat-message-tool"]}
> >
{tool.isError === false ? ( {tool.isError === false ? (

View File

@@ -21,7 +21,6 @@ import {
} from "./artifacts"; } from "./artifacts";
import { useChatStore } from "../store"; import { useChatStore } from "../store";
import { IconButton } from "./button"; import { IconButton } from "./button";
import { useAppConfig } from "../store/config"; import { useAppConfig } from "../store/config";
export function Mermaid(props: { code: string }) { export function Mermaid(props: { code: string }) {
@@ -207,6 +206,23 @@ function CustomCode(props: { children: any; className?: string }) {
); );
} }
function escapeDollarNumber(text: string) {
let escapedText = "";
for (let i = 0; i < text.length; i += 1) {
let char = text[i];
const nextChar = text[i + 1] || " ";
if (char === "$" && nextChar >= "0" && nextChar <= "9") {
char = "\\$";
}
escapedText += char;
}
return escapedText;
}
function escapeBrackets(text: string) { function escapeBrackets(text: string) {
const pattern = const pattern =
/(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g; /(```[\s\S]*?```|`.*?`)|\\\[([\s\S]*?[^\\])\\\]|\\\((.*?)\\\)/g;
@@ -235,7 +251,7 @@ function tryWrapHtmlCode(text: string) {
}, },
) )
.replace( .replace(
/(<\/body>)([\r\n\s]*?)(<\/html>)([\n\r]*)([`]*)([\n\r]*?)/g, /(<\/body>)([\r\n\s]*?)(<\/html>)([\n\r]*?)([`]*?)([\n\r]*?)/g,
(match, bodyEnd, space, htmlEnd, newLine, quoteEnd) => { (match, bodyEnd, space, htmlEnd, newLine, quoteEnd) => {
return !quoteEnd ? bodyEnd + space + htmlEnd + "\n```\n" : match; return !quoteEnd ? bodyEnd + space + htmlEnd + "\n```\n" : match;
}, },
@@ -244,7 +260,7 @@ function tryWrapHtmlCode(text: string) {
function _MarkDownContent(props: { content: string }) { function _MarkDownContent(props: { content: string }) {
const escapedContent = useMemo(() => { const escapedContent = useMemo(() => {
return tryWrapHtmlCode(escapeBrackets(props.content)); return tryWrapHtmlCode(escapeBrackets(escapeDollarNumber(props.content)));
}, [props.content]); }, [props.content]);
return ( return (
@@ -266,20 +282,6 @@ function _MarkDownContent(props: { content: string }) {
p: (pProps) => <p {...pProps} dir="auto" />, p: (pProps) => <p {...pProps} dir="auto" />,
a: (aProps) => { a: (aProps) => {
const href = aProps.href || ""; const href = aProps.href || "";
if (/\.(aac|mp3|opus|wav)$/.test(href)) {
return (
<figure>
<audio controls src={href}></audio>
</figure>
);
}
if (/\.(3gp|3g2|webm|ogv|mpeg|mp4|avi)$/.test(href)) {
return (
<video controls width="99.9%">
<source src={href} />
</video>
);
}
const isInternal = /^\/#/i.test(href); const isInternal = /^\/#/i.test(href);
const target = isInternal ? "_self" : aProps.target ?? "_blank"; const target = isInternal ? "_self" : aProps.target ?? "_blank";
return <a {...aProps} target={target} />; return <a {...aProps} target={target} />;

View File

@@ -1,7 +0,0 @@
.select-compress-model {
width: 60%;
select {
max-width: 100%;
white-space: normal;
}
}

View File

@@ -6,7 +6,6 @@ import { InputRange } from "./input-range";
import { ListItem, Select } from "./ui-lib"; import { ListItem, Select } from "./ui-lib";
import { useAllModels } from "../utils/hooks"; import { useAllModels } from "../utils/hooks";
import { groupBy } from "lodash-es"; import { groupBy } from "lodash-es";
import styles from "./model-config.module.scss";
export function ModelConfigList(props: { export function ModelConfigList(props: {
modelConfig: ModelConfig; modelConfig: ModelConfig;
@@ -243,7 +242,6 @@ export function ModelConfigList(props: {
subTitle={Locale.Settings.CompressModel.SubTitle} subTitle={Locale.Settings.CompressModel.SubTitle}
> >
<Select <Select
className={styles["select-compress-model"]}
aria-label={Locale.Settings.CompressModel.Title} aria-label={Locale.Settings.CompressModel.Title}
value={compressModelValue} value={compressModelValue}
onChange={(e) => { onChange={(e) => {

View File

@@ -72,9 +72,3 @@
} }
} }
} }
.subtitle-button {
button {
overflow:visible ;
}
}

View File

@@ -9,7 +9,6 @@ import CopyIcon from "../icons/copy.svg";
import ClearIcon from "../icons/clear.svg"; import ClearIcon from "../icons/clear.svg";
import LoadingIcon from "../icons/three-dots.svg"; import LoadingIcon from "../icons/three-dots.svg";
import EditIcon from "../icons/edit.svg"; import EditIcon from "../icons/edit.svg";
import FireIcon from "../icons/fire.svg";
import EyeIcon from "../icons/eye.svg"; import EyeIcon from "../icons/eye.svg";
import DownloadIcon from "../icons/download.svg"; import DownloadIcon from "../icons/download.svg";
import UploadIcon from "../icons/upload.svg"; import UploadIcon from "../icons/upload.svg";
@@ -19,7 +18,7 @@ import ConfirmIcon from "../icons/confirm.svg";
import ConnectionIcon from "../icons/connection.svg"; import ConnectionIcon from "../icons/connection.svg";
import CloudSuccessIcon from "../icons/cloud-success.svg"; import CloudSuccessIcon from "../icons/cloud-success.svg";
import CloudFailIcon from "../icons/cloud-fail.svg"; import CloudFailIcon from "../icons/cloud-fail.svg";
import { trackSettingsPageGuideToCPaymentClick } from "../utils/auth-settings-events";
import { import {
Input, Input,
List, List,
@@ -70,7 +69,6 @@ import {
UPDATE_URL, UPDATE_URL,
Stability, Stability,
Iflytek, Iflytek,
SAAS_CHAT_URL,
} from "../constant"; } from "../constant";
import { Prompt, SearchService, usePromptStore } from "../store/prompt"; import { Prompt, SearchService, usePromptStore } from "../store/prompt";
import { ErrorBoundary } from "./error"; import { ErrorBoundary } from "./error";
@@ -688,31 +686,6 @@ export function Settings() {
</ListItem> </ListItem>
); );
const saasStartComponent = (
<ListItem
className={styles["subtitle-button"]}
title={
Locale.Settings.Access.SaasStart.Title +
`${Locale.Settings.Access.SaasStart.Label}`
}
subTitle={Locale.Settings.Access.SaasStart.SubTitle}
>
<IconButton
aria={
Locale.Settings.Access.SaasStart.Title +
Locale.Settings.Access.SaasStart.ChatNow
}
icon={<FireIcon />}
type={"primary"}
text={Locale.Settings.Access.SaasStart.ChatNow}
onClick={() => {
trackSettingsPageGuideToCPaymentClick();
window.location.href = SAAS_CHAT_URL;
}}
/>
</ListItem>
);
const useCustomConfigComponent = // Conditionally render the following ListItem based on clientConfig.isApp const useCustomConfigComponent = // Conditionally render the following ListItem based on clientConfig.isApp
!clientConfig?.isApp && ( // only show if isApp is false !clientConfig?.isApp && ( // only show if isApp is false
<ListItem <ListItem
@@ -1585,7 +1558,6 @@ export function Settings() {
</List> </List>
<List id={SlotID.CustomModel}> <List id={SlotID.CustomModel}>
{saasStartComponent}
{accessCodeComponent} {accessCodeComponent}
{!accessStore.hideUserApiKey && ( {!accessStore.hideUserApiKey && (

View File

@@ -62,14 +62,14 @@
} }
} }
&.vertical { &.vertical{
flex-direction: column; flex-direction: column;
align-items: start; align-items: start;
.list-header { .list-header{
.list-item-title { .list-item-title{
margin-bottom: 5px; margin-bottom: 5px;
} }
.list-item-sub-title { .list-item-sub-title{
margin-bottom: 2px; margin-bottom: 2px;
} }
} }
@@ -310,7 +310,7 @@
justify-content: center; justify-content: center;
z-index: 999; z-index: 999;
.selector-item-disabled { .selector-item-disabled{
opacity: 0.6; opacity: 0.6;
} }
@@ -336,4 +336,3 @@
} }
} }
} }

View File

@@ -10,7 +10,7 @@ export const getBuildConfig = () => {
const buildMode = process.env.BUILD_MODE ?? "standalone"; const buildMode = process.env.BUILD_MODE ?? "standalone";
const isApp = !!process.env.BUILD_APP; const isApp = !!process.env.BUILD_APP;
const version = "v" + tauriConfig.package.version; const version = "v" + tauriConfig.version;
const commitInfo = (() => { const commitInfo = (() => {
try { try {

View File

@@ -500,6 +500,3 @@ export const PLUGINS = [
{ name: "Stable Diffusion", path: Path.Sd }, { name: "Stable Diffusion", path: Path.Sd },
{ name: "Search Chat", path: Path.SearchChat }, { name: "Search Chat", path: Path.SearchChat },
]; ];
export const SAAS_CHAT_URL = "https://nextchat.dev/chat";
export const SAAS_CHAT_UTM_URL = "https://nextchat.dev/chat?utm=github";

View File

@@ -1 +0,0 @@
<svg class="icon--SJP_d" width="16" height="16" fill="none" viewBox="0 0 16 16" style="min-width: 16px; min-height: 16px;"><g><path data-follow-fill="currentColor" fill-rule="evenodd" clip-rule="evenodd" d="M5.248 14.444a.625.625 0 0 1-.005-.884l5.068-5.12a.625.625 0 0 0 0-.88L5.243 2.44a.625.625 0 1 1 .889-.88l5.067 5.121c.723.73.723 1.907 0 2.638l-5.067 5.12a.625.625 0 0 1-.884.005Z" fill="currentColor"></path></g></svg>

Before

Width:  |  Height:  |  Size: 426 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="M12.832 21.801c3.126-.626 7.168-2.875 7.168-8.69c0-5.291-3.873-8.815-6.658-10.434c-.619-.36-1.342.113-1.342.828v1.828c0 1.442-.606 4.074-2.29 5.169c-.86.559-1.79-.278-1.894-1.298l-.086-.838c-.1-.974-1.092-1.565-1.87-.971C4.461 8.46 3 10.33 3 13.11C3 20.221 8.289 22 10.933 22q.232 0 .484-.015C10.111 21.874 8 21.064 8 18.444c0-2.05 1.495-3.435 2.631-4.11c.306-.18.663.055.663.41v.59c0 .45.175 1.155.59 1.637c.47.546 1.159-.026 1.214-.744c.018-.226.246-.37.442-.256c.641.375 1.46 1.175 1.46 2.473c0 2.048-1.129 2.99-2.168 3.357"/></svg>

Before

Width:  |  Height:  |  Size: 648 B

View File

@@ -1,19 +0,0 @@
<svg width="38.73" height="42" viewBox="0 0 221 240" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="160.697" y="38.125" width="65.007" height="145.932" rx="32.503" transform="rotate(21.987 160.697 38.125)" fill="url(#logo_svg__a)"></rect>
<path fill-rule="evenodd" clip-rule="evenodd" d="m48.642 79.125-25.92 71.213c-6.139 16.869 2.558 35.52 19.427 41.66 16.868 6.14 35.52-2.558 41.66-19.426L94.23 143.94l-36.658-37.439a32.42 32.42 0 0 1-9.244-23.497c.033-1.326.14-2.62.314-3.879Z" fill="url(#logo_svg__b)"></path>
<path d="M172.578 132.787a32.765 32.765 0 0 1 8.981 24.238c-1.458 28.748-36.622 41.778-56.46 20.92l-67.644-71.122a32.763 32.763 0 0 1-8.981-24.238c1.457-28.748 36.622-41.778 56.46-20.92l67.644 71.122Z" fill="url(#logo_svg__c)" fill-opacity="0.96"></path>
<defs>
<linearGradient id="logo_svg__a" x1="215.063" y1="59.628" x2="160.714" y2="157.96" gradientUnits="userSpaceOnUse">
<stop stop-color="#3EADFE"></stop>
<stop offset="1" stop-color="#2A7AFF"></stop>
</linearGradient>
<linearGradient id="logo_svg__b" x1="105.376" y1="84.416" x2="19.745" y2="131.163" gradientUnits="userSpaceOnUse">
<stop stop-color="#01B3FF"></stop>
<stop offset="1" stop-color="#59ECFA"></stop>
</linearGradient>
<linearGradient id="logo_svg__c" x1="102.734" y1="136.396" x2="192.577" y2="155.859" gradientUnits="userSpaceOnUse">
<stop stop-color="#023BFF" stop-opacity="0.82"></stop>
<stop offset="0.88" stop-color="#2D86FF" stop-opacity="0.76"></stop>
</linearGradient>
</defs>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const ar: PartialLocaleType = { const ar: PartialLocaleType = {
WIP: "قريبًا...", WIP: "قريبًا...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 واجهت المحادثة بعض المشكلات، لا داعي للقلق: ? "تم اكتشاف مفتاح API غير صالح، يرجى الذهاب إلى [الإعدادات](/#/settings) للتحقق من صحة مفتاح API."
\\ 1⃣ إذا كنت ترغب في تجربة دون إعداد، [انقر هنا لبدء المحادثة فورًا 🚀](${SAAS_CHAT_UTM_URL}) : "كلمة المرور غير صحيحة أو فارغة، يرجى الذهاب إلى [تسجيل الدخول](/#/auth) لإدخال كلمة مرور صحيحة، أو أدخل مفتاح OpenAI API الخاص بك في [الإعدادات](/#/settings).",
\\ 2⃣ إذا كنت تريد استخدام موارد OpenAI الخاصة بك، انقر [هنا](/#/settings) لتعديل الإعدادات ⚙️`
: `😆 واجهت المحادثة بعض المشكلات، لا داعي للقلق:
\ 1⃣ إذا كنت ترغب في تجربة دون إعداد، [انقر هنا لبدء المحادثة فورًا 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ إذا كنت تستخدم إصدار النشر الخاص، انقر [هنا](/#/auth) لإدخال مفتاح الوصول 🔑
\ 3⃣ إذا كنت تريد استخدام موارد OpenAI الخاصة بك، انقر [هنا](/#/settings) لتعديل الإعدادات ⚙️
`,
}, },
Auth: { Auth: {
Title: "تحتاج إلى كلمة مرور", Title: "تحتاج إلى كلمة مرور",
@@ -24,10 +18,6 @@ const ar: PartialLocaleType = {
Input: "أدخل رمز الوصول هنا", Input: "أدخل رمز الوصول هنا",
Confirm: "تأكيد", Confirm: "تأكيد",
Later: "في وقت لاحق", Later: "في وقت لاحق",
Return: "عودة",
SaasTips: "الإعدادات معقدة، أريد استخدامه على الفور",
TopTips:
"🥳 عرض NextChat AI الأول، افتح الآن OpenAI o1, GPT-4o, Claude-3.5 وأحدث النماذج الكبيرة",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} محادثة`, ChatItemCount: (count: number) => `${count} محادثة`,
@@ -291,13 +281,6 @@ const ar: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "استخدام NextChat AI",
Label: "(أفضل حل من حيث التكلفة)",
SubTitle:
"مدعوم رسميًا من NextChat، جاهز للاستخدام بدون إعداد، يدعم أحدث النماذج الكبيرة مثل OpenAI o1 و GPT-4o و Claude-3.5",
ChatNow: "الدردشة الآن",
},
AccessCode: { AccessCode: {
Title: "كلمة المرور للوصول", Title: "كلمة المرور للوصول",
SubTitle: "قام المشرف بتمكين الوصول المشفر", SubTitle: "قام المشرف بتمكين الوصول المشفر",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const bn: PartialLocaleType = { const bn: PartialLocaleType = {
WIP: "শীঘ্রই আসছে...", WIP: "শীঘ্রই আসছে...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 কথোপকথনে কিছু সমস্যা হয়েছে, চিন্তার কিছু নেই: ? "অবৈধ API কী সনাক্ত করা হয়েছে, অনুগ্রহ করে [সেটিংস](/#/settings) পৃষ্ঠায় যান এবং নিশ্চিত করুন যে API কী সঠিকভাবে কনফিগার করা হয়েছে।"
\\ 1⃣ যদি আপনি শূন্য কনফিগারেশনে শুরু করচান, তাহলে [এখানে ক্লিক করে অবিলম্বে কথোপকথন শুরু করুন 🚀](${SAAS_CHAT_UTM_URL}) : "অ্যাক্সেস পাসওয়ার্ড সঠিক নয় বা খালি, অনুগ্রহ করে [লগইন](/#/auth) পৃষ্ঠায় যান এবং সঠিক অ্যাক্সেস পাসওয়ার্ড প্রবেশ করান, অথবা [সেটিংস](/#/settings) পৃষ্ঠায় আপনার OpenAI API কী প্রবেশ করান।",
\\ 2⃣ যদি আপনি আপনার নিজস্ব OpenAI সম্পদ ব্যবহার করতে চান, তাহলে [এখানে ক্লিক করুন](/#/settings) সেটিংস পরিবর্তন করতে ⚙️`
: `😆 কথোপকথনে কিছু সমস্যা হয়েছে, চিন্তার কিছু নেই:
\ 1⃣ যদি আপনি শূন্য কনফিগারেশনে শুরু করতে চান, তাহলে [এখানে ক্লিক করে অবিলম্বে কথোপকথন শুরু করুন 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ যদি আপনি একটি প্রাইভেট ডেপ্লয়মেন্ট সংস্করণ ব্যবহার করেন, তাহলে [এখানে ক্লিক করুন](/#/auth) প্রবেশাধিকার কীগুলি প্রবেশ করতে 🔑
\ 3⃣ যদি আপনি আপনার নিজস্ব OpenAI সম্পদ ব্যবহার করতে চান, তাহলে [এখানে ক্লিক করুন](/#/settings) সেটিংস পরিবর্তন করতে ⚙️
`,
}, },
Auth: { Auth: {
Title: "পাসওয়ার্ড প্রয়োজন", Title: "পাসওয়ার্ড প্রয়োজন",
@@ -24,10 +18,6 @@ const bn: PartialLocaleType = {
Input: "এখানে অ্যাক্সেস কোড লিখুন", Input: "এখানে অ্যাক্সেস কোড লিখুন",
Confirm: "নিশ্চিত করুন", Confirm: "নিশ্চিত করুন",
Later: "পরে বলুন", Later: "পরে বলুন",
Return: "ফিরে আসা",
SaasTips: "কনফিগারেশন খুব কঠিন, আমি অবিলম্বে ব্যবহার করতে চাই",
TopTips:
"🥳 NextChat AI প্রথম প্রকাশের অফার, এখনই OpenAI o1, GPT-4o, Claude-3.5 এবং সর্বশেষ বড় মডেলগুলি আনলক করুন",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} টি চ্যাট`, ChatItemCount: (count: number) => `${count} টি চ্যাট`,
@@ -294,14 +284,6 @@ const bn: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "NextChat AI ব্যবহার করুন",
Label: "(সেরা মূল্যসাশ্রয়ী সমাধান)",
SubTitle:
"NextChat কর্তৃক অফিসিয়াল রক্ষণাবেক্ষণ, শূন্য কনফিগারেশন ব্যবহার শুরু করুন, OpenAI o1, GPT-4o, Claude-3.5 সহ সর্বশেষ বড় মডেলগুলি সমর্থন করে",
ChatNow: "এখনই চ্যাট করুন",
},
AccessCode: { AccessCode: {
Title: "অ্যাক্সেস পাসওয়ার্ড", Title: "অ্যাক্সেস পাসওয়ার্ড",
SubTitle: "অ্যাডমিন এনক্রিপ্টেড অ্যাক্সেস সক্রিয় করেছেন", SubTitle: "অ্যাডমিন এনক্রিপ্টেড অ্যাক্সেস সক্রিয় করেছেন",

View File

@@ -1,6 +1,5 @@
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
@@ -8,26 +7,16 @@ const cn = {
WIP: "该功能仍在开发中……", WIP: "该功能仍在开发中……",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 对话遇到了一些问题,不用慌: ? "检测到无效 API Key请前往[设置](/#/settings)页检查 API Key 是否配置正确。"
\\ 1⃣ 想要零配置开箱即用,[点击这里立刻开启对话 🚀](${SAAS_CHAT_UTM_URL}) : "访问密码不正确或为空,请前往[登录](/#/auth)页输入正确的访问密码,或者在[设置](/#/settings)页填入你自己的 OpenAI API Key。",
\\ 2⃣ 如果你想消耗自己的 OpenAI 资源,点击[这里](/#/settings)修改设置 ⚙️`
: `😆 对话遇到了一些问题,不用慌:
\ 1⃣ 想要零配置开箱即用,[点击这里立刻开启对话 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ 如果你正在使用私有部署版本,点击[这里](/#/auth)输入访问秘钥 🔑
\ 3⃣ 如果你想消耗自己的 OpenAI 资源,点击[这里](/#/settings)修改设置 ⚙️
`,
}, },
Auth: { Auth: {
Return: "返回",
Title: "需要密码", Title: "需要密码",
Tips: "管理员开启了密码验证,请在下方填入访问码", Tips: "管理员开启了密码验证,请在下方填入访问码",
SubTips: "或者输入你的 OpenAI 或 Google AI 密钥", SubTips: "或者输入你的 OpenAI 或 Google API 密钥",
Input: "在此处填写访问码", Input: "在此处填写访问码",
Confirm: "确认", Confirm: "确认",
Later: "稍后再说", Later: "稍后再说",
SaasTips: "配置太麻烦,想要立即使用",
TopTips:
"🥳 NextChat AI 首发优惠,立刻解锁 OpenAI o1, GPT-4o, Claude-3.5 等最新大模型",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} 条对话`, ChatItemCount: (count: number) => `${count} 条对话`,
@@ -308,13 +297,6 @@ const cn = {
}, },
Access: { Access: {
SaasStart: {
Title: "使用 NextChat AI",
Label: "(性价比最高的方案)",
SubTitle:
"由 NextChat 官方维护, 零配置开箱即用,支持 OpenAI o1, GPT-4o, Claude-3.5 等最新大模型",
ChatNow: "立刻对话",
},
AccessCode: { AccessCode: {
Title: "访问密码", Title: "访问密码",
SubTitle: "管理员已开启加密访问", SubTitle: "管理员已开启加密访问",
@@ -378,7 +360,7 @@ const cn = {
ApiKey: { ApiKey: {
Title: "API 密钥", Title: "API 密钥",
SubTitle: "从 Google AI 获取您的 API 密钥", SubTitle: "从 Google AI 获取您的 API 密钥",
Placeholder: "Google AI API KEY", Placeholder: "输入您的 Google AI Studio API 密钥",
}, },
Endpoint: { Endpoint: {

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const cs: PartialLocaleType = { const cs: PartialLocaleType = {
WIP: "V přípravě...", WIP: "V přípravě...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Rozhovor narazil na nějaké problémy, nebojte se: ? "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."
\\ 1⃣ Pokud chcete začít bez konfigurace, [klikněte sem pro okamžitý začátek chatu 🚀](${SAAS_CHAT_UTM_URL}) : "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.",
\\ 2⃣ Pokud chcete využít své vlastní zdroje OpenAI, klikněte [sem](/#/settings) a upravte nastavení ⚙️`
: `😆 Rozhovor narazil na nějaké problémy, nebojte se:
\ 1⃣ Pokud chcete začít bez konfigurace, [klikněte sem pro okamžitý začátek chatu 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Pokud používáte verzi soukromého nasazení, klikněte [sem](/#/auth) a zadejte přístupový klíč 🔑
\ 3⃣ Pokud chcete využít své vlastní zdroje OpenAI, klikněte [sem](/#/settings) a upravte nastavení ⚙️
`,
}, },
Auth: { Auth: {
Title: "Potřebné heslo", Title: "Potřebné heslo",
@@ -24,10 +18,6 @@ const cs: PartialLocaleType = {
Input: "Zadejte přístupový kód zde", Input: "Zadejte přístupový kód zde",
Confirm: "Potvrdit", Confirm: "Potvrdit",
Later: "Později", Later: "Později",
Return: "Návrat",
SaasTips: "Konfigurace je příliš složitá, chci okamžitě začít používat",
TopTips:
"🥳 Uvítací nabídka NextChat AI, okamžitě odemkněte OpenAI o1, GPT-4o, Claude-3.5 a nejnovější velké modely",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} konverzací`, ChatItemCount: (count: number) => `${count} konverzací`,
@@ -294,14 +284,6 @@ const cs: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Použití NextChat AI",
Label: "(Nejlepší nákladově efektivní řešení)",
SubTitle:
"Oficiálně udržováno NextChat, připraveno k použití bez konfigurace, podporuje nejnovější velké modely jako OpenAI o1, GPT-4o, Claude-3.5",
ChatNow: "Začněte chatovat nyní",
},
AccessCode: { AccessCode: {
Title: "Přístupový kód", Title: "Přístupový kód",
SubTitle: "Administrátor aktivoval šifrovaný přístup", SubTitle: "Administrátor aktivoval šifrovaný přístup",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const de: PartialLocaleType = { const de: PartialLocaleType = {
WIP: "In Bearbeitung...", WIP: "In Bearbeitung...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Das Gespräch hatte einige Probleme, keine Sorge: ? "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."
\\ 1⃣ Wenn du ohne Konfiguration sofort starten möchtest, [klicke hier, um sofort zu chatten 🚀](${SAAS_CHAT_UTM_URL}) : "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.",
\\ 2⃣ Wenn du deine eigenen OpenAI-Ressourcen verwenden möchtest, klicke [hier](/#/settings), um die Einstellungen zu ändern ⚙️`
: `😆 Das Gespräch hatte einige Probleme, keine Sorge:
\ 1⃣ Wenn du ohne Konfiguration sofort starten möchtest, [klicke hier, um sofort zu chatten 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Wenn du eine private Bereitstellung verwendest, klicke [hier](/#/auth), um den Zugriffsschlüssel einzugeben 🔑
\ 3⃣ Wenn du deine eigenen OpenAI-Ressourcen verwenden möchtest, klicke [hier](/#/settings), um die Einstellungen zu ändern ⚙️
`,
}, },
Auth: { Auth: {
Title: "Passwort erforderlich", Title: "Passwort erforderlich",
@@ -24,11 +18,6 @@ const de: PartialLocaleType = {
Input: "Geben Sie hier den Zugangscode ein", Input: "Geben Sie hier den Zugangscode ein",
Confirm: "Bestätigen", Confirm: "Bestätigen",
Later: "Später", Later: "Später",
Return: "Zurück",
SaasTips:
"Die Konfiguration ist zu kompliziert, ich möchte es sofort nutzen",
TopTips:
"🥳 NextChat AI Einführungsangebot, schalte jetzt OpenAI o1, GPT-4o, Claude-3.5 und die neuesten großen Modelle frei",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} Gespräche`, ChatItemCount: (count: number) => `${count} Gespräche`,
@@ -302,14 +291,6 @@ const de: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "NextChat AI verwenden",
Label: "(Die kosteneffektivste Lösung)",
SubTitle:
"Offiziell von NextChat verwaltet, sofort einsatzbereit ohne Konfiguration, unterstützt die neuesten großen Modelle wie OpenAI o1, GPT-4o und Claude-3.5",
ChatNow: "Jetzt chatten",
},
AccessCode: { AccessCode: {
Title: "Zugangscode", Title: "Zugangscode",
SubTitle: SubTitle:

View File

@@ -1,7 +1,7 @@
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import { LocaleType } from "./index"; import { LocaleType } from "./index";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
// if you are adding a new translation, please use PartialLocaleType instead of LocaleType // if you are adding a new translation, please use PartialLocaleType instead of LocaleType
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
@@ -9,26 +9,16 @@ const en: LocaleType = {
WIP: "Coming Soon...", WIP: "Coming Soon...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Oops, there's an issue. No worries: ? "Invalid API Key, please check it in [Settings](/#/settings) page."
\\ 1⃣ New here? [Click to start chatting now 🚀](${SAAS_CHAT_UTM_URL}) : "Unauthorized access, please enter access code in [auth](/#/auth) page, or enter your OpenAI API Key.",
\\ 2⃣ Want to use your own OpenAI resources? [Click here](/#/settings) to change settings ⚙️`
: `😆 Oops, there's an issue. Let's fix it:
\ 1⃣ New here? [Click to start chatting now 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Using a private setup? [Click here](/#/auth) to enter your key 🔑
\ 3⃣ Want to use your own OpenAI resources? [Click here](/#/settings) to change settings ⚙️
`,
}, },
Auth: { Auth: {
Return: "Return",
Title: "Need Access Code", Title: "Need Access Code",
Tips: "Please enter access code below", Tips: "Please enter access code below",
SubTips: "Or enter your OpenAI or Google API Key", SubTips: "Or enter your OpenAI or Google API Key",
Input: "access code", Input: "access code",
Confirm: "Confirm", Confirm: "Confirm",
Later: "Later", Later: "Later",
SaasTips: "Too Complex, Use Immediately Now",
TopTips:
"🥳 NextChat AI launch promotion: Instantly unlock the latest models like OpenAI o1, GPT-4o, Claude-3.5!",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} messages`, ChatItemCount: (count: number) => `${count} messages`,
@@ -311,14 +301,6 @@ const en: LocaleType = {
NoAccess: "Enter API Key to check balance", NoAccess: "Enter API Key to check balance",
}, },
Access: { Access: {
SaasStart: {
Title: "Use NextChat AI",
Label: " (Most Cost-Effective Option)",
SubTitle:
"Maintained by NextChat, zero setup needed, unlock OpenAI o1, GPT-4o," +
" Claude-3.5 and more",
ChatNow: "Start Now",
},
AccessCode: { AccessCode: {
Title: "Access Code", Title: "Access Code",
SubTitle: "Access control Enabled", SubTitle: "Access control Enabled",
@@ -479,7 +461,7 @@ const en: LocaleType = {
ApiKey: { ApiKey: {
Title: "API Key", Title: "API Key",
SubTitle: "Obtain your API Key from Google AI", SubTitle: "Obtain your API Key from Google AI",
Placeholder: "Google AI API Key", Placeholder: "Enter your Google AI Studio API Key",
}, },
Endpoint: { Endpoint: {

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const es: PartialLocaleType = { const es: PartialLocaleType = {
WIP: "En construcción...", WIP: "En construcción...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 La conversación encontró algunos problemas, no te preocupes: ? "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."
\\ 1⃣ Si deseas comenzar sin configuración, [haz clic aquí para empezar a chatear inmediatamente 🚀](${SAAS_CHAT_UTM_URL}) : "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.",
\\ 2⃣ Si deseas usar tus propios recursos de OpenAI, haz clic [aquí](/#/settings) para modificar la configuración ⚙️`
: `😆 La conversación encontró algunos problemas, no te preocupes:
\ 1⃣ Si deseas comenzar sin configuración, [haz clic aquí para empezar a chatear inmediatamente 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Si estás utilizando una versión de implementación privada, haz clic [aquí](/#/auth) para ingresar la clave de acceso 🔑
\ 3⃣ Si deseas usar tus propios recursos de OpenAI, haz clic [aquí](/#/settings) para modificar la configuración ⚙️
`,
}, },
Auth: { Auth: {
Title: "Se requiere contraseña", Title: "Se requiere contraseña",
@@ -24,11 +18,6 @@ const es: PartialLocaleType = {
Input: "Introduce el código de acceso aquí", Input: "Introduce el código de acceso aquí",
Confirm: "Confirmar", Confirm: "Confirmar",
Later: "Más tarde", Later: "Más tarde",
Return: "Regresar",
SaasTips:
"La configuración es demasiado complicada, quiero usarlo de inmediato",
TopTips:
"🥳 Oferta de lanzamiento de NextChat AI, desbloquea OpenAI o1, GPT-4o, Claude-3.5 y los últimos grandes modelos",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} conversaciones`, ChatItemCount: (count: number) => `${count} conversaciones`,
@@ -305,14 +294,6 @@ const es: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Use NextChat AI",
Label: "(The most cost-effective solution)",
SubTitle:
"Officially maintained by NextChat, zero configuration ready to use, supports the latest large models like OpenAI o1, GPT-4o, and Claude-3.5",
ChatNow: "Chat Now",
},
AccessCode: { AccessCode: {
Title: "Contraseña de acceso", Title: "Contraseña de acceso",
SubTitle: "El administrador ha habilitado el acceso encriptado", SubTitle: "El administrador ha habilitado el acceso encriptado",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const fr: PartialLocaleType = { const fr: PartialLocaleType = {
WIP: "Prochainement...", WIP: "Prochainement...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 La conversation a rencontré quelques problèmes, pas de panique : ? "Clé API invalide détectée. Veuillez vérifier si la clé API est correctement configurée dans la page [Paramètres](/#/settings)."
\\ 1⃣ Si vous souhaitez commencer sans configuration, [cliquez ici pour démarrer la conversation immédiatement 🚀](${SAAS_CHAT_UTM_URL}) : "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).",
\\ 2⃣ Si vous souhaitez utiliser vos propres ressources OpenAI, cliquez [ici](/#/settings) pour modifier les paramètres ⚙️`
: `😆 La conversation a rencontré quelques problèmes, pas de panique :
\ 1⃣ Si vous souhaitez commencer sans configuration, [cliquez ici pour démarrer la conversation immédiatement 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Si vous utilisez une version déployée privée, cliquez [ici](/#/auth) pour entrer la clé d'accès 🔑
\ 3⃣ Si vous souhaitez utiliser vos propres ressources OpenAI, cliquez [ici](/#/settings) pour modifier les paramètres ⚙️
`,
}, },
Auth: { Auth: {
Title: "Mot de passe requis", Title: "Mot de passe requis",
@@ -24,11 +18,6 @@ const fr: PartialLocaleType = {
Input: "Entrez le code d'accès ici", Input: "Entrez le code d'accès ici",
Confirm: "Confirmer", Confirm: "Confirmer",
Later: "Plus tard", Later: "Plus tard",
Return: "Retour",
SaasTips:
"La configuration est trop compliquée, je veux l'utiliser immédiatement",
TopTips:
"🥳 Offre de lancement NextChat AI, débloquez OpenAI o1, GPT-4o, Claude-3.5 et les derniers grands modèles",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} conversations`, ChatItemCount: (count: number) => `${count} conversations`,
@@ -305,14 +294,6 @@ const fr: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Utiliser NextChat AI",
Label: "(La solution la plus rentable)",
SubTitle:
"Officiellement maintenu par NextChat, prêt à l'emploi sans configuration, prend en charge les derniers grands modèles comme OpenAI o1, GPT-4o et Claude-3.5",
ChatNow: "Discuter maintenant",
},
AccessCode: { AccessCode: {
Title: "Mot de passe d'accès", Title: "Mot de passe d'accès",
SubTitle: "L'administrateur a activé l'accès sécurisé", SubTitle: "L'administrateur a activé l'accès sécurisé",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const id: PartialLocaleType = { const id: PartialLocaleType = {
WIP: "Coming Soon...", WIP: "Coming Soon...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Percakapan mengalami beberapa masalah, tidak perlu khawatir: ? "API Key tidak valid terdeteksi, silakan periksa apakah API Key telah dikonfigurasi dengan benar di halaman [Pengaturan](/#/settings)."
\\ 1⃣ Jika Anda ingin memulai tanpa konfigurasi, [klik di sini untuk mulai mengobrol segera 🚀](${SAAS_CHAT_UTM_URL}) : "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).",
\\ 2⃣ Jika Anda ingin menggunakan sumber daya OpenAI Anda sendiri, klik [di sini](/#/settings) untuk mengubah pengaturan ⚙️`
: `😆 Percakapan mengalami beberapa masalah, tidak perlu khawatir:
\ 1⃣ Jika Anda ingin memulai tanpa konfigurasi, [klik di sini untuk mulai mengobrol segera 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Jika Anda menggunakan versi penyebaran pribadi, klik [di sini](/#/auth) untuk memasukkan kunci akses 🔑
\ 3⃣ Jika Anda ingin menggunakan sumber daya OpenAI Anda sendiri, klik [di sini](/#/settings) untuk mengubah pengaturan ⚙️
`,
}, },
Auth: { Auth: {
Title: "Kebutuhan Kata Sandi", Title: "Kebutuhan Kata Sandi",
@@ -24,10 +18,6 @@ const id: PartialLocaleType = {
Input: "Masukkan kode akses di sini", Input: "Masukkan kode akses di sini",
Confirm: "Konfirmasi", Confirm: "Konfirmasi",
Later: "Nanti", Later: "Nanti",
Return: "Kembali",
SaasTips: "Konfigurasi terlalu rumit, saya ingin menggunakannya segera",
TopTips:
"🥳 Penawaran Peluncuran NextChat AI, buka OpenAI o1, GPT-4o, Claude-3.5 dan model besar terbaru sekarang",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} percakapan`, ChatItemCount: (count: number) => `${count} percakapan`,
@@ -295,14 +285,6 @@ const id: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Gunakan NextChat AI",
Label: "(Solusi paling hemat biaya)",
SubTitle:
"Dikelola secara resmi oleh NextChat, siap digunakan tanpa konfigurasi, mendukung model besar terbaru seperti OpenAI o1, GPT-4o, dan Claude-3.5",
ChatNow: "Chat Sekarang",
},
AccessCode: { AccessCode: {
Title: "Kata Sandi Akses", Title: "Kata Sandi Akses",
SubTitle: "Administrator telah mengaktifkan akses terenkripsi", SubTitle: "Administrator telah mengaktifkan akses terenkripsi",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const it: PartialLocaleType = { const it: PartialLocaleType = {
WIP: "Work in progress...", WIP: "Work in progress...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 La conversazione ha incontrato alcuni problemi, non preoccuparti: ? "API Key non valido rilevato. Vai alla pagina [Impostazioni](/#/settings) per controllare se l'API Key è configurata correttamente."
\\ 1⃣ Se vuoi iniziare senza configurazione, [clicca qui per iniziare a chattare immediatamente 🚀](${SAAS_CHAT_UTM_URL}) : "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).",
\\ 2⃣ Se vuoi utilizzare le tue risorse OpenAI, clicca [qui](/#/settings) per modificare le impostazioni ⚙️`
: `😆 La conversazione ha incontrato alcuni problemi, non preoccuparti:
\ 1⃣ Se vuoi iniziare senza configurazione, [clicca qui per iniziare a chattare immediatamente 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Se stai utilizzando una versione di distribuzione privata, clicca [qui](/#/auth) per inserire la chiave di accesso 🔑
\ 3⃣ Se vuoi utilizzare le tue risorse OpenAI, clicca [qui](/#/settings) per modificare le impostazioni ⚙️
`,
}, },
Auth: { Auth: {
Title: "Password richiesta", Title: "Password richiesta",
@@ -24,11 +18,6 @@ const it: PartialLocaleType = {
Input: "Inserisci il codice di accesso qui", Input: "Inserisci il codice di accesso qui",
Confirm: "Conferma", Confirm: "Conferma",
Later: "Più tardi", Later: "Più tardi",
Return: "Ritorna",
SaasTips:
"La configurazione è troppo complicata, voglio usarlo immediatamente",
TopTips:
"🥳 Offerta di lancio NextChat AI, sblocca OpenAI o1, GPT-4o, Claude-3.5 e i più recenti modelli di grandi dimensioni",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} conversazioni`, ChatItemCount: (count: number) => `${count} conversazioni`,
@@ -306,14 +295,6 @@ const it: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Usa NextChat AI",
Label: "(La soluzione più conveniente)",
SubTitle:
"Mantenuto ufficialmente da NextChat, pronto all'uso senza configurazione, supporta i modelli più recenti come OpenAI o1, GPT-4o e Claude-3.5",
ChatNow: "Chatta ora",
},
AccessCode: { AccessCode: {
Title: "Password di accesso", Title: "Password di accesso",
SubTitle: "L'amministratore ha abilitato l'accesso criptato", SubTitle: "L'amministratore ha abilitato l'accesso criptato",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const jp: PartialLocaleType = { const jp: PartialLocaleType = {
WIP: "この機能は開発中です", WIP: "この機能は開発中です",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 会話中に問題が発生しましたが、心配しないでください: ? "無効なAPIキーが検出されました。[設定](/#/settings)ページでAPIキーが正しく設定されているか確認してください。"
\\ 1⃣ 設定なしで始めたい場合は、[ここをクリックしてすぐにチャットを開始 🚀](${SAAS_CHAT_UTM_URL}) : "アクセスパスワードが正しくないか空です。[ログイン](/#/auth)ページで正しいアクセスパスワードを入力するか、[設定](/#/settings)ページで自分のOpenAI APIキーを入力してください。",
\\ 2⃣ 自分のOpenAIリソースを使用したい場合は、[ここをクリックして](/#/settings)設定を変更してください ⚙️`
: `😆 会話中に問題が発生しましたが、心配しないでください:
\ 1⃣ 設定なしで始めたい場合は、[ここをクリックしてすぐにチャットを開始 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ プライベートデプロイ版を使用している場合は、[ここをクリックして](/#/auth)アクセストークンを入力してください 🔑
\ 3⃣ 自分のOpenAIリソースを使用したい場合は、[ここをクリックして](/#/settings)設定を変更してください ⚙️
`,
}, },
Auth: { Auth: {
Title: "パスワードが必要です", Title: "パスワードが必要です",
@@ -24,10 +18,6 @@ const jp: PartialLocaleType = {
Input: "ここにアクセスコードを入力", Input: "ここにアクセスコードを入力",
Confirm: "確認", Confirm: "確認",
Later: "後で", Later: "後で",
Return: "戻る",
SaasTips: "設定が面倒すぎる、すぐに使いたい",
TopTips:
"🥳 NextChat AIの発売特典で、OpenAI o1、GPT-4o、Claude-3.5などの最新の大規模モデルを今すぐアンロック",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count}件の会話`, ChatItemCount: (count: number) => `${count}件の会話`,
@@ -292,14 +282,6 @@ const jp: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "NextChat AIを使用する",
Label: "(コストパフォーマンスの最も高いソリューション)",
SubTitle:
"NextChatによって公式に管理されており、設定なしですぐに使用でき、OpenAI o1、GPT-4o、Claude-3.5などの最新の大規模モデルをサポートしています",
ChatNow: "今すぐチャット",
},
AccessCode: { AccessCode: {
Title: "アクセスパスワード", Title: "アクセスパスワード",
SubTitle: "管理者が暗号化アクセスを有効にしました", SubTitle: "管理者が暗号化アクセスを有効にしました",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const ko: PartialLocaleType = { const ko: PartialLocaleType = {
WIP: "곧 출시 예정...", WIP: "곧 출시 예정...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 대화 중 문제가 발생했습니다, 걱정하지 마세요: ? "유효하지 않은 API 키가 감지되었습니다. [설정](/#/settings) 페이지에서 API 키가 올바르게 구성되었는지 확인하십시오."
\\ 1⃣ 제로 구성으로 시작하고 싶다면, [여기를 클릭하여 즉시 대화를 시작하세요 🚀](${SAAS_CHAT_UTM_URL}) : "잘못된 접근 비밀번호이거나 비밀번호가 비어 있습니다. [로그인](/#/auth) 페이지에서 올바른 접근 비밀번호를 입력하거나 [설정](/#/settings) 페이지에서 OpenAI API 키를 입력하십시오.",
\\ 2⃣ 자신의 OpenAI 리소스를 사용하고 싶다면, [여기를 클릭하여](/#/settings) 설정을 수정하세요 ⚙️`
: `😆 대화 중 문제가 발생했습니다, 걱정하지 마세요:
\ 1⃣ 제로 구성으로 시작하고 싶다면, [여기를 클릭하여 즉시 대화를 시작하세요 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ 개인 배포 버전을 사용하고 있다면, [여기를 클릭하여](/#/auth) 접근 키를 입력하세요 🔑
\ 3⃣ 자신의 OpenAI 리소스를 사용하고 싶다면, [여기를 클릭하여](/#/settings) 설정을 수정하세요 ⚙️
`,
}, },
Auth: { Auth: {
Title: "비밀번호 필요", Title: "비밀번호 필요",
@@ -24,10 +18,6 @@ const ko: PartialLocaleType = {
Input: "여기에 접근 코드를 입력하십시오.", Input: "여기에 접근 코드를 입력하십시오.",
Confirm: "확인", Confirm: "확인",
Later: "나중에 하기", Later: "나중에 하기",
Return: "돌아가기",
SaasTips: "설정이 너무 복잡합니다. 즉시 사용하고 싶습니다.",
TopTips:
"🥳 NextChat AI 출시 기념 할인, 지금 OpenAI o1, GPT-4o, Claude-3.5 및 최신 대형 모델을 해제하세요",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} 개의 대화`, ChatItemCount: (count: number) => `${count} 개의 대화`,
@@ -291,14 +281,6 @@ const ko: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "NextChat AI 사용하기",
Label: "(가장 비용 효율적인 솔루션)",
SubTitle:
"NextChat에 의해 공식적으로 유지 관리되며, 제로 구성으로 즉시 사용할 수 있으며, OpenAI o1, GPT-4o, Claude-3.5와 같은 최신 대형 모델을 지원합니다",
ChatNow: "지금 채팅하기",
},
AccessCode: { AccessCode: {
Title: "접근 비밀번호", Title: "접근 비밀번호",
SubTitle: "관리자가 암호화된 접근을 활성화했습니다.", SubTitle: "관리자가 암호화된 접근을 활성화했습니다.",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const no: PartialLocaleType = { const no: PartialLocaleType = {
WIP: "Arbeid pågår ...", WIP: "Arbeid pågår ...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Samtalen har støtt på noen problemer, ikke bekymre deg: ? "Ugyldig API-nøkkel oppdaget. Gå til [innstillinger](/#/settings) for å sjekke om API-nøkkelen er riktig konfigurert."
\\ 1⃣ Hvis du vil starte uten konfigurasjon, [klikk her for å begynne å chatte umiddelbart 🚀](${SAAS_CHAT_UTM_URL}) : "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.",
\\ 2⃣ Hvis du vil bruke dine egne OpenAI-ressurser, klikk [her](/#/settings) for å endre innstillingene ⚙️`
: `😆 Samtalen har støtt på noen problemer, ikke bekymre deg:
\ 1⃣ Hvis du vil starte uten konfigurasjon, [klikk her for å begynne å chatte umiddelbart 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Hvis du bruker en privat distribusjonsversjon, klikk [her](/#/auth) for å skrive inn tilgangsnøkkelen 🔑
\ 3⃣ Hvis du vil bruke dine egne OpenAI-ressurser, klikk [her](/#/settings) for å endre innstillingene ⚙️
`,
}, },
Auth: { Auth: {
Title: "Passord påkrevd", Title: "Passord påkrevd",
@@ -24,11 +18,6 @@ const no: PartialLocaleType = {
Input: "Skriv tilgangskoden her", Input: "Skriv tilgangskoden her",
Confirm: "Bekreft", Confirm: "Bekreft",
Later: "Kom tilbake senere", Later: "Kom tilbake senere",
Return: "Tilbake",
SaasTips:
"Konfigurasjonen er for komplisert, jeg vil bruke det med en gang",
TopTips:
"🥳 NextChat AI lanseringstilbud, lås opp OpenAI o1, GPT-4o, Claude-3.5 og de nyeste store modellene nå",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} samtaler`, ChatItemCount: (count: number) => `${count} samtaler`,
@@ -299,14 +288,6 @@ const no: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Bruk NextChat AI",
Label: "(Den mest kostnadseffektive løsningen)",
SubTitle:
"Offisielt vedlikeholdt av NextChat, klar til bruk uten konfigurasjon, støtter de nyeste store modellene som OpenAI o1, GPT-4o og Claude-3.5",
ChatNow: "Chat nå",
},
AccessCode: { AccessCode: {
Title: "Adgangskode", Title: "Adgangskode",
SubTitle: "Administrator har aktivert kryptert tilgang", SubTitle: "Administrator har aktivert kryptert tilgang",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import { PartialLocaleType } from "../locales/index"; import { PartialLocaleType } from "../locales/index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const pt: PartialLocaleType = { const pt: PartialLocaleType = {
WIP: "Em breve...", WIP: "Em breve...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 A conversa encontrou alguns problemas, não se preocupe: ? "Chave API inválida, por favor verifique em [Configurações](/#/settings)."
\\ 1⃣ Se você quiser começar sem configuração, [clique aqui para começar a conversar imediatamente 🚀](${SAAS_CHAT_UTM_URL}) : "Acesso não autorizado, por favor insira o código de acesso em [auth](/#/auth) ou insira sua Chave API OpenAI.",
\\ 2⃣ Se você deseja usar seus próprios recursos OpenAI, clique [aqui](/#/settings) para modificar as configurações ⚙️`
: `😆 A conversa encontrou alguns problemas, não se preocupe:
\ 1⃣ Se você quiser começar sem configuração, [clique aqui para começar a conversar imediatamente 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Se você estiver usando uma versão de implantação privada, clique [aqui](/#/auth) para inserir a chave de acesso 🔑
\ 3⃣ Se você deseja usar seus próprios recursos OpenAI, clique [aqui](/#/settings) para modificar as configurações ⚙️
`,
}, },
Auth: { Auth: {
Title: "Necessário Código de Acesso", Title: "Necessário Código de Acesso",
@@ -24,10 +18,6 @@ const pt: PartialLocaleType = {
Input: "código de acesso", Input: "código de acesso",
Confirm: "Confirmar", Confirm: "Confirmar",
Later: "Depois", Later: "Depois",
Return: "Voltar",
SaasTips: "A configuração é muito complicada, quero usá-la imediatamente",
TopTips:
"🥳 Oferta de Lançamento do NextChat AI, desbloqueie o OpenAI o1, GPT-4o, Claude-3.5 e os mais recentes grandes modelos agora",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} mensagens`, ChatItemCount: (count: number) => `${count} mensagens`,
@@ -291,14 +281,6 @@ const pt: PartialLocaleType = {
NoAccess: "Insira a Chave API para verificar o saldo", NoAccess: "Insira a Chave API para verificar o saldo",
}, },
Access: { Access: {
SaasStart: {
Title: "Usar NextChat AI",
Label: "(A solução mais econômica)",
SubTitle:
"Mantido oficialmente pelo NextChat, pronto para uso sem configuração, suporta os mais recentes grandes modelos como OpenAI o1, GPT-4o e Claude-3.5",
ChatNow: "Conversar agora",
},
AccessCode: { AccessCode: {
Title: "Código de Acesso", Title: "Código de Acesso",
SubTitle: "Controle de Acesso Habilitado", SubTitle: "Controle de Acesso Habilitado",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import { PartialLocaleType } from "../locales/index"; import { PartialLocaleType } from "../locales/index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const ru: PartialLocaleType = { const ru: PartialLocaleType = {
WIP: "Скоро...", WIP: "Скоро...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 В разговоре возникли некоторые проблемы, не переживайте: ? "Обнаружен недействительный API-ключ. Пожалуйста, перейдите на страницу [Настройки](/#/settings), чтобы проверить правильность конфигурации API-ключа."
\\ 1⃣ Если вы хотите начать без настройки, [нажмите здесь, чтобы немедленно начать разговор 🚀](${SAAS_CHAT_UTM_URL}) : "Неверный или пустой пароль доступа. Пожалуйста, перейдите на страницу [Вход](/#/auth), чтобы ввести правильный пароль доступа, или на страницу [Настройки](/#/settings), чтобы ввести ваш собственный API-ключ OpenAI.",
\\ 2⃣ Если вы хотите использовать свои ресурсы OpenAI, нажмите [здесь](/#/settings), чтобы изменить настройки ⚙️`
: `😆 В разговоре возникли некоторые проблемы, не переживайте:
\ 1⃣ Если вы хотите начать без настройки, [нажмите здесь, чтобы немедленно начать разговор 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Если вы используете частную версию развертывания, нажмите [здесь](/#/auth), чтобы ввести ключ доступа 🔑
\ 3⃣ Если вы хотите использовать свои ресурсы OpenAI, нажмите [здесь](/#/settings), чтобы изменить настройки ⚙️
`,
}, },
Auth: { Auth: {
Title: "Требуется пароль", Title: "Требуется пароль",
@@ -24,10 +18,6 @@ const ru: PartialLocaleType = {
Input: "Введите код доступа здесь", Input: "Введите код доступа здесь",
Confirm: "Подтвердить", Confirm: "Подтвердить",
Later: "Позже", Later: "Позже",
Return: "Назад",
SaasTips: "Настройка слишком сложна, я хочу использовать это немедленно",
TopTips:
"🥳 Предложение по запуску NextChat AI: разблокируйте OpenAI o1, GPT-4o, Claude-3.5 и новейшие большие модели прямо сейчас",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} бесед`, ChatItemCount: (count: number) => `${count} бесед`,
@@ -296,14 +286,6 @@ const ru: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Используйте NextChat AI",
Label: "(Самое экономичное решение)",
SubTitle:
"Официально поддерживается NextChat, готов к использованию без настройки, поддерживает последние крупные модели, такие как OpenAI o1, GPT-4o и Claude-3.5",
ChatNow: "Начать чат",
},
AccessCode: { AccessCode: {
Title: "Пароль доступа", Title: "Пароль доступа",
SubTitle: "Администратор включил защиту паролем", SubTitle: "Администратор включил защиту паролем",

View File

@@ -1,7 +1,7 @@
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
// if you are adding a new translation, please use PartialLocaleType instead of LocaleType // if you are adding a new translation, please use PartialLocaleType instead of LocaleType
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
@@ -9,14 +9,8 @@ const sk: PartialLocaleType = {
WIP: "Už čoskoro...", WIP: "Už čoskoro...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Rozhovor narazil na nejaké problémy, nebojte sa: ? "Neplatný API kľúč, prosím skontrolujte ho na stránke [Nastavenia](/#/settings)."
\\ 1⃣ Ak chcete začať bez konfigurácie, [kliknite sem, aby ste okamžite začali chatovať 🚀](${SAAS_CHAT_UTM_URL}) : "Neoprávnený prístup, prosím zadajte prístupový kód na stránke [auth](/#/auth), alebo zadajte váš OpenAI API kľúč.",
\\ 2⃣ Ak chcete používať svoje vlastné zdroje OpenAI, kliknite [sem](/#/settings), aby ste upravili nastavenia ⚙️`
: `😆 Rozhovor narazil na nejaké problémy, nebojte sa:
\ 1⃣ Ak chcete začať bez konfigurácie, [kliknite sem, aby ste okamžite začali chatovať 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Ak používate verziu súkromného nasadenia, kliknite [sem](/#/auth), aby ste zadali prístupový kľúč 🔑
\ 3⃣ Ak chcete používať svoje vlastné zdroje OpenAI, kliknite [sem](/#/settings), aby ste upravili nastavenia ⚙️
`,
}, },
Auth: { Auth: {
Title: "Potrebný prístupový kód", Title: "Potrebný prístupový kód",
@@ -25,10 +19,6 @@ const sk: PartialLocaleType = {
Input: "prístupový kód", Input: "prístupový kód",
Confirm: "Potvrdiť", Confirm: "Potvrdiť",
Later: "Neskôr", Later: "Neskôr",
Return: "Návrat",
SaasTips: "Nastavenie je príliš zložité, chcem to okamžite použiť",
TopTips:
"🥳 Uvítacia ponuka NextChat AI, okamžite odomknite OpenAI o1, GPT-4o, Claude-3.5 a najnovšie veľké modely",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} správ`, ChatItemCount: (count: number) => `${count} správ`,
@@ -291,14 +281,6 @@ const sk: PartialLocaleType = {
NoAccess: "Zadajte API kľúč na skontrolovanie zostatku", NoAccess: "Zadajte API kľúč na skontrolovanie zostatku",
}, },
Access: { Access: {
SaasStart: {
Title: "Použite NextChat AI",
Label: "(Najvýhodnejšie riešenie)",
SubTitle:
"Oficiálne udržiavané NextChat, pripravené na použitie bez konfigurácie, podporuje najnovšie veľké modely ako OpenAI o1, GPT-4o a Claude-3.5",
ChatNow: "Chatovať teraz",
},
AccessCode: { AccessCode: {
Title: "Prístupový kód", Title: "Prístupový kód",
SubTitle: "Povolený prístupový kód", SubTitle: "Povolený prístupový kód",

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const tr: PartialLocaleType = { const tr: PartialLocaleType = {
WIP: "Çalışma devam ediyor...", WIP: "Çalışma devam ediyor...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Sohbet bazı sorunlarla karşılaştı, endişelenmeyin: ? "Geçersiz API Anahtarı tespit edildi, lütfen API Anahtarını doğru şekilde yapılandırmak için [Ayarlar](/#/settings) sayfasına gidin."
\\ 1⃣ Eğer sıfır yapılandırma ile başlamak istiyorsanız, [buraya tıklayarak hemen sohbete başlayın 🚀](${SAAS_CHAT_UTM_URL}) : "Erişim şifresi yanlış veya boş, lütfen doğru erişim şifresini girmek için [Giriş](/#/auth) sayfasına gidin veya kendi OpenAI API Anahtarınızı [Ayarlar](/#/settings) sayfasına girin.",
\\ 2⃣ Kendi OpenAI kaynaklarınızı kullanmak istiyorsanız, [buraya tıklayarak](/#/settings) ayarları değiştirin ⚙️`
: `😆 Sohbet bazı sorunlarla karşılaştı, endişelenmeyin:
\ 1⃣ Eğer sıfır yapılandırma ile başlamak istiyorsanız, [buraya tıklayarak hemen sohbete başlayın 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Eğer özel dağıtım sürümü kullanıyorsanız, [buraya tıklayarak](/#/auth) erişim anahtarını girin 🔑
\ 3⃣ Kendi OpenAI kaynaklarınızı kullanmak istiyorsanız, [buraya tıklayarak](/#/settings) ayarları değiştirin ⚙️
`,
}, },
Auth: { Auth: {
Title: "Şifre Gerekli", Title: "Şifre Gerekli",
@@ -24,10 +18,6 @@ const tr: PartialLocaleType = {
Input: "Erişim kodunu buraya girin", Input: "Erişim kodunu buraya girin",
Confirm: "Onayla", Confirm: "Onayla",
Later: "Sonra", Later: "Sonra",
Return: "Geri",
SaasTips: "Ayarlar çok karmaşık, hemen kullanmak istiyorum",
TopTips:
"🥳 NextChat AI lansman teklifi, OpenAI o1, GPT-4o, Claude-3.5 ve en son büyük modelleri şimdi açın",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} konuşma`, ChatItemCount: (count: number) => `${count} konuşma`,
@@ -296,14 +286,6 @@ const tr: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "NextChat AI kullanın",
Label: "(En maliyet etkin çözüm)",
SubTitle:
"NextChat tarafından resmi olarak yönetilmektedir, yapılandırma olmadan hemen kullanıma hazırdır, OpenAI o1, GPT-4o, Claude-3.5 gibi en son büyük modelleri destekler",
ChatNow: "Şimdi sohbet et",
},
AccessCode: { AccessCode: {
Title: "Erişim Şifresi", Title: "Erişim Şifresi",
SubTitle: "Yönetici şifreli erişimi etkinleştirdi", SubTitle: "Yönetici şifreli erişimi etkinleştirdi",

View File

@@ -1,20 +1,14 @@
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const tw = { const tw = {
WIP: "此功能仍在開發中……", WIP: "此功能仍在開發中……",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 對話遇到了一些問題,不用慌: ? "偵測到無效的 API Key請前往[設定](/#/settings)頁面檢查 API Key 是否設定正確。"
\\ 1⃣ 想要無須設定開箱即用,[點選這裡立刻開啟對話 🚀](${SAAS_CHAT_UTM_URL}) : "存取密碼不正確或尚未填寫,請前往[登入](/#/auth)頁面輸入正確的存取密碼,或者在[設定](/#/settings)頁面填入你自己的 OpenAI API Key。",
\\ 2⃣ 如果你想消耗自己的 OpenAI 資源,點選[這裡](/#/settings)修改設定 ⚙️`
: `😆 對話遇到了一些問題,不用慌:
\ 1⃣ 想要無須設定開箱即用,[點選這裡立刻開啟對話 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ 如果你正在使用私有部署版本,點選[這裡](/#/auth)輸入存取金鑰 🔑
\ 3⃣ 如果你想消耗自己的 OpenAI 資源,點選[這裡](/#/settings)修改設定 ⚙️
`,
}, },
Auth: { Auth: {
@@ -24,10 +18,6 @@ const tw = {
Input: "在此處填寫存取密碼", Input: "在此處填寫存取密碼",
Confirm: "確認", Confirm: "確認",
Later: "稍候再說", Later: "稍候再說",
Return: "返回",
SaasTips: "設定太麻煩,想要立即使用",
TopTips:
"🥳 NextChat AI 首發優惠,立刻解鎖 OpenAI o1, GPT-4o, Claude-3.5 等最新的大型語言模型",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} 則對話`, ChatItemCount: (count: number) => `${count} 則對話`,
@@ -53,8 +43,8 @@ const tw = {
PinToastAction: "檢視", PinToastAction: "檢視",
Delete: "刪除", Delete: "刪除",
Edit: "編輯", Edit: "編輯",
RefreshTitle: "重新整理標題", RefreshTitle: "刷新標題",
RefreshToast: "已傳送重新整理標題請求", RefreshToast: "已發送刷新標題請求",
}, },
Commands: { Commands: {
new: "新建聊天", new: "新建聊天",
@@ -95,10 +85,10 @@ const tw = {
IsContext: "預設提示詞", IsContext: "預設提示詞",
ShortcutKey: { ShortcutKey: {
Title: "鍵盤快捷方式", Title: "鍵盤快捷方式",
newChat: "開新聊天", newChat: "開新聊天",
focusInput: "聚焦輸入框", focusInput: "聚焦輸入框",
copyLastMessage: "複製最後一個回覆", copyLastMessage: "複製最後一個回覆",
copyLastCode: "複製最後一個程式碼區塊", copyLastCode: "複製最後一個代碼塊",
showShortcutKey: "顯示快捷方式", showShortcutKey: "顯示快捷方式",
}, },
}, },
@@ -174,9 +164,9 @@ const tw = {
SubTitle: "聊天內容的字型大小", SubTitle: "聊天內容的字型大小",
}, },
FontFamily: { FontFamily: {
Title: "聊天字", Title: "聊天字",
SubTitle: "聊天內容的字,若空則用全域預設字型", SubTitle: "聊天內容的字,若空則用全局默認字體",
Placeholder: "字名稱", Placeholder: "字名稱",
}, },
InjectSystemPrompts: { InjectSystemPrompts: {
Title: "匯入系統提示", Title: "匯入系統提示",
@@ -297,14 +287,6 @@ const tw = {
}, },
Access: { Access: {
SaasStart: {
Title: "使用 NextChat AI",
Label: "(性價比最高的方案)",
SubTitle:
"由 NextChat 官方維護,無須設定開箱即用,支援 OpenAI o1、GPT-4o、Claude-3.5 等最新的大型語言模型",
ChatNow: "立刻開始對話",
},
AccessCode: { AccessCode: {
Title: "存取密碼", Title: "存取密碼",
SubTitle: "管理員已開啟加密存取", SubTitle: "管理員已開啟加密存取",
@@ -485,18 +467,18 @@ const tw = {
}, },
}, },
SearchChat: { SearchChat: {
Name: "搜", Name: "搜",
Page: { Page: {
Title: "搜聊天記錄", Title: "搜聊天記錄",
Search: "輸入搜關鍵詞", Search: "輸入搜關鍵詞",
NoResult: "沒有找到結果", NoResult: "沒有找到結果",
NoData: "沒有資料", NoData: "沒有數據",
Loading: "載中", Loading: "載中",
SubTitle: (count: number) => `找到 ${count} 條結果`, SubTitle: (count: number) => `找到 ${count} 條結果`,
}, },
Item: { Item: {
View: "檢視", View: "查看",
}, },
}, },
NewChat: { NewChat: {

View File

@@ -1,21 +1,15 @@
import { SubmitKey } from "../store/config"; import { SubmitKey } from "../store/config";
import type { PartialLocaleType } from "./index"; import type { PartialLocaleType } from "./index";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import { SAAS_CHAT_UTM_URL } from "@/app/constant";
const isApp = !!getClientConfig()?.isApp; const isApp = !!getClientConfig()?.isApp;
const vi: PartialLocaleType = { const vi: PartialLocaleType = {
WIP: "Sắp ra mắt...", WIP: "Sắp ra mắt...",
Error: { Error: {
Unauthorized: isApp Unauthorized: isApp
? `😆 Cuộc trò chuyện gặp một số vấn đề, đừng lo lắng: ? "Phát hiện khóa API không hợp lệ, vui lòng truy cập trang [Cài đặt](/#/settings) để kiểm tra xem khóa API có được cấu hình chính xác không."
\\ 1⃣ Nếu bạn muốn bắt đầu mà không cần cấu hình, [nhấp vào đây để bắt đầu trò chuyện ngay lập tức 🚀](${SAAS_CHAT_UTM_URL}) : "Mật khẩu truy cập không đúng hoặc để trống, vui lòng truy cập trang [Đăng nhập](/#/auth) để nhập mật khẩu truy cập chính xác, hoặc điền khóa API OpenAI của bạn vào trang [Cài đặt](/#/settings).",
\\ 2⃣ Nếu bạn muốn sử dụng tài nguyên OpenAI của riêng mình, hãy nhấp [vào đây](/#/settings) để thay đổi cài đặt ⚙️`
: `😆 Cuộc trò chuyện gặp một số vấn đề, đừng lo lắng:
\ 1⃣ Nếu bạn muốn bắt đầu mà không cần cấu hình, [nhấp vào đây để bắt đầu trò chuyện ngay lập tức 🚀](${SAAS_CHAT_UTM_URL})
\ 2⃣ Nếu bạn đang sử dụng phiên bản triển khai riêng, hãy nhấp [vào đây](/#/auth) để nhập khóa truy cập 🔑
\ 3⃣ Nếu bạn muốn sử dụng tài nguyên OpenAI của riêng mình, hãy nhấp [vào đây](/#/settings) để thay đổi cài đặt ⚙️
`,
}, },
Auth: { Auth: {
Title: "Cần mật khẩu", Title: "Cần mật khẩu",
@@ -24,10 +18,6 @@ const vi: PartialLocaleType = {
Input: "Nhập mã truy cập tại đây", Input: "Nhập mã truy cập tại đây",
Confirm: "Xác nhận", Confirm: "Xác nhận",
Later: "Để sau", Later: "Để sau",
Return: "Trở lại",
SaasTips: "Cấu hình quá phức tạp, tôi muốn sử dụng ngay lập tức",
TopTips:
"🥳 Ưu đãi ra mắt NextChat AI, mở khóa OpenAI o1, GPT-4o, Claude-3.5 và các mô hình lớn mới nhất ngay bây giờ",
}, },
ChatItem: { ChatItem: {
ChatItemCount: (count: number) => `${count} cuộc trò chuyện`, ChatItemCount: (count: number) => `${count} cuộc trò chuyện`,
@@ -293,14 +283,6 @@ const vi: PartialLocaleType = {
}, },
Access: { Access: {
SaasStart: {
Title: "Sử dụng NextChat AI",
Label: "(Giải pháp tiết kiệm chi phí nhất)",
SubTitle:
"Được NextChat chính thức duy trì, sẵn sàng sử dụng mà không cần cấu hình, hỗ trợ các mô hình lớn mới nhất như OpenAI o1, GPT-4o và Claude-3.5",
ChatNow: "Chat ngay",
},
AccessCode: { AccessCode: {
Title: "Mật khẩu truy cập", Title: "Mật khẩu truy cập",
SubTitle: "Quản trị viên đã bật truy cập mã hóa", SubTitle: "Quản trị viên đã bật truy cập mã hóa",

View File

@@ -1,18 +1,8 @@
import { import {
ApiPath,
GoogleSafetySettingsThreshold, GoogleSafetySettingsThreshold,
ServiceProvider, ServiceProvider,
StoreKey, StoreKey,
ApiPath,
OPENAI_BASE_URL,
ANTHROPIC_BASE_URL,
GEMINI_BASE_URL,
BAIDU_BASE_URL,
BYTEDANCE_BASE_URL,
ALIBABA_BASE_URL,
TENCENT_BASE_URL,
MOONSHOT_BASE_URL,
STABILITY_BASE_URL,
IFLYTEK_BASE_URL,
} from "../constant"; } from "../constant";
import { getHeaders } from "../client/api"; import { getHeaders } from "../client/api";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
@@ -24,26 +14,6 @@ let fetchState = 0; // 0 not fetch, 1 fetching, 2 done
const isApp = getClientConfig()?.buildMode === "export"; const isApp = getClientConfig()?.buildMode === "export";
const DEFAULT_OPENAI_URL = isApp ? OPENAI_BASE_URL : ApiPath.OpenAI;
const DEFAULT_GOOGLE_URL = isApp ? GEMINI_BASE_URL : ApiPath.Google;
const DEFAULT_ANTHROPIC_URL = isApp ? ANTHROPIC_BASE_URL : ApiPath.Anthropic;
const DEFAULT_BAIDU_URL = isApp ? BAIDU_BASE_URL : ApiPath.Baidu;
const DEFAULT_BYTEDANCE_URL = isApp ? BYTEDANCE_BASE_URL : ApiPath.ByteDance;
const DEFAULT_ALIBABA_URL = isApp ? ALIBABA_BASE_URL : ApiPath.Alibaba;
const DEFAULT_TENCENT_URL = isApp ? TENCENT_BASE_URL : ApiPath.Tencent;
const DEFAULT_MOONSHOT_URL = isApp ? MOONSHOT_BASE_URL : ApiPath.Moonshot;
const DEFAULT_STABILITY_URL = isApp ? STABILITY_BASE_URL : ApiPath.Stability;
const DEFAULT_IFLYTEK_URL = isApp ? IFLYTEK_BASE_URL : ApiPath.Iflytek;
const DEFAULT_ACCESS_STATE = { const DEFAULT_ACCESS_STATE = {
accessCode: "", accessCode: "",
useCustomConfig: false, useCustomConfig: false,
@@ -51,7 +21,7 @@ const DEFAULT_ACCESS_STATE = {
provider: ServiceProvider.OpenAI, provider: ServiceProvider.OpenAI,
// openai // openai
openaiUrl: DEFAULT_OPENAI_URL, openaiUrl: ApiPath.OpenAI as string,
openaiApiKey: "", openaiApiKey: "",
// azure // azure
@@ -60,44 +30,44 @@ const DEFAULT_ACCESS_STATE = {
azureApiVersion: "2023-08-01-preview", azureApiVersion: "2023-08-01-preview",
// google ai studio // google ai studio
googleUrl: DEFAULT_GOOGLE_URL, googleUrl: ApiPath.Google as string,
googleApiKey: "", googleApiKey: "",
googleApiVersion: "v1", googleApiVersion: "v1",
googleSafetySettings: GoogleSafetySettingsThreshold.BLOCK_ONLY_HIGH, googleSafetySettings: GoogleSafetySettingsThreshold.BLOCK_ONLY_HIGH,
// anthropic // anthropic
anthropicUrl: DEFAULT_ANTHROPIC_URL, anthropicUrl: ApiPath.Anthropic as string,
anthropicApiKey: "", anthropicApiKey: "",
anthropicApiVersion: "2023-06-01", anthropicApiVersion: "2023-06-01",
// baidu // baidu
baiduUrl: DEFAULT_BAIDU_URL, baiduUrl: ApiPath.Baidu as string,
baiduApiKey: "", baiduApiKey: "",
baiduSecretKey: "", baiduSecretKey: "",
// bytedance // bytedance
bytedanceUrl: DEFAULT_BYTEDANCE_URL, bytedanceUrl: ApiPath.ByteDance as string,
bytedanceApiKey: "", bytedanceApiKey: "",
// alibaba // alibaba
alibabaUrl: DEFAULT_ALIBABA_URL, alibabaUrl: ApiPath.Alibaba as string,
alibabaApiKey: "", alibabaApiKey: "",
// moonshot // moonshot
moonshotUrl: DEFAULT_MOONSHOT_URL, moonshotUrl: ApiPath.Moonshot as string,
moonshotApiKey: "", moonshotApiKey: "",
//stability //stability
stabilityUrl: DEFAULT_STABILITY_URL, stabilityUrl: ApiPath.Stability as string,
stabilityApiKey: "", stabilityApiKey: "",
// tencent // tencent
tencentUrl: DEFAULT_TENCENT_URL, tencentUrl: ApiPath.Tencent as string,
tencentSecretKey: "", tencentSecretKey: "",
tencentSecretId: "", tencentSecretId: "",
// iflytek // iflytek
iflytekUrl: DEFAULT_IFLYTEK_URL, iflytekUrl: ApiPath.Iflytek as string,
iflytekApiKey: "", iflytekApiKey: "",
iflytekApiSecret: "", iflytekApiSecret: "",
@@ -200,13 +170,10 @@ export const useAccessStore = createPersistStore(
}) })
.then((res) => res.json()) .then((res) => res.json())
.then((res) => { .then((res) => {
const defaultModel = res.defaultModel ?? ""; // Set default model from env request
if (defaultModel !== "") { let defaultModel = res.defaultModel ?? "";
const [model, providerName] = defaultModel.split("@"); if (defaultModel !== "")
DEFAULT_CONFIG.modelConfig.model = model; DEFAULT_CONFIG.modelConfig.model = defaultModel;
DEFAULT_CONFIG.modelConfig.providerName = providerName;
}
return res; return res;
}) })
.then((res: DangerConfig) => { .then((res: DangerConfig) => {

View File

@@ -16,9 +16,6 @@ import {
DEFAULT_SYSTEM_TEMPLATE, DEFAULT_SYSTEM_TEMPLATE,
KnowledgeCutOffDate, KnowledgeCutOffDate,
StoreKey, StoreKey,
SUMMARIZE_MODEL,
GEMINI_SUMMARIZE_MODEL,
ServiceProvider,
} from "../constant"; } from "../constant";
import Locale, { getLang } from "../locales"; import Locale, { getLang } from "../locales";
import { isDalle3, safeLocalStorage } from "../utils"; import { isDalle3, safeLocalStorage } from "../utils";
@@ -26,8 +23,6 @@ import { prettyObject } from "../utils/format";
import { createPersistStore } from "../utils/store"; import { createPersistStore } from "../utils/store";
import { estimateTokenLength } from "../utils/token"; import { estimateTokenLength } from "../utils/token";
import { ModelConfig, ModelType, useAppConfig } from "./config"; import { ModelConfig, ModelType, useAppConfig } from "./config";
import { useAccessStore } from "./access";
import { collectModelsWithDefaultModel } from "../utils/model";
import { createEmptyMask, Mask } from "./mask"; import { createEmptyMask, Mask } from "./mask";
const localStorage = safeLocalStorage(); const localStorage = safeLocalStorage();
@@ -42,7 +37,6 @@ export type ChatMessageTool = {
}; };
content?: string; content?: string;
isError?: boolean; isError?: boolean;
errorMsg?: string;
}; };
export type ChatMessage = RequestMessage & { export type ChatMessage = RequestMessage & {
@@ -108,35 +102,6 @@ function createEmptySession(): ChatSession {
}; };
} }
function getSummarizeModel(
currentModel: string,
providerName: string,
): string[] {
// if it is using gpt-* models, force to use 4o-mini to summarize
if (currentModel.startsWith("gpt") || currentModel.startsWith("chatgpt")) {
const configStore = useAppConfig.getState();
const accessStore = useAccessStore.getState();
const allModel = collectModelsWithDefaultModel(
configStore.models,
[configStore.customModels, accessStore.customModels].join(","),
accessStore.defaultModel,
);
const summarizeModel = allModel.find(
(m) => m.name === SUMMARIZE_MODEL && m.available,
);
if (summarizeModel) {
return [
summarizeModel.name,
summarizeModel.provider?.providerName as string,
];
}
}
if (currentModel.startsWith("gemini")) {
return [GEMINI_SUMMARIZE_MODEL, ServiceProvider.Google];
}
return [currentModel, providerName];
}
function countMessages(msgs: ChatMessage[]) { function countMessages(msgs: ChatMessage[]) {
return msgs.reduce( return msgs.reduce(
(pre, cur) => pre + estimateTokenLength(getMessageTextContent(cur)), (pre, cur) => pre + estimateTokenLength(getMessageTextContent(cur)),
@@ -613,14 +578,8 @@ export const useChatStore = createPersistStore(
return; return;
} }
// if not config compressModel, then using getSummarizeModel const providerName = modelConfig.compressProviderName;
const [model, providerName] = modelConfig.compressModel const api: ClientApi = getClientApi(providerName);
? [modelConfig.compressModel, modelConfig.compressProviderName]
: getSummarizeModel(
session.mask.modelConfig.model,
session.mask.modelConfig.providerName,
);
const api: ClientApi = getClientApi(providerName as ServiceProvider);
// remove error messages if any // remove error messages if any
const messages = session.messages; const messages = session.messages;
@@ -651,12 +610,11 @@ export const useChatStore = createPersistStore(
api.llm.chat({ api.llm.chat({
messages: topicMessages, messages: topicMessages,
config: { config: {
model, model: modelConfig.compressModel,
stream: false, stream: false,
providerName, providerName,
}, },
onFinish(message) { onFinish(message) {
if (!isValidMessage(message)) return;
get().updateCurrentSession( get().updateCurrentSession(
(session) => (session) =>
(session.topic = (session.topic =
@@ -715,8 +673,7 @@ export const useChatStore = createPersistStore(
config: { config: {
...modelcfg, ...modelcfg,
stream: true, stream: true,
model, model: modelConfig.compressModel,
providerName,
}, },
onUpdate(message) { onUpdate(message) {
session.memoryPrompt = message; session.memoryPrompt = message;
@@ -733,10 +690,6 @@ export const useChatStore = createPersistStore(
}, },
}); });
} }
function isValidMessage(message: any): boolean {
return typeof message === "string" && !message.startsWith("```json");
}
}, },
updateStat(message: ChatMessage) { updateStat(message: ChatMessage) {
@@ -769,7 +722,7 @@ export const useChatStore = createPersistStore(
}, },
{ {
name: StoreKey.Chat, name: StoreKey.Chat,
version: 3.3, version: 3.2,
migrate(persistedState, version) { migrate(persistedState, version) {
const state = persistedState as any; const state = persistedState as any;
const newState = JSON.parse( const newState = JSON.parse(
@@ -825,14 +778,6 @@ export const useChatStore = createPersistStore(
config.modelConfig.compressProviderName; config.modelConfig.compressProviderName;
}); });
} }
// revert default summarize model for every session
if (version < 3.3) {
newState.sessions.forEach((s) => {
const config = useAppConfig.getState();
s.mask.modelConfig.compressModel = "";
s.mask.modelConfig.compressProviderName = "";
});
}
return newState as any; return newState as any;
}, },

View File

@@ -65,14 +65,14 @@ export const DEFAULT_CONFIG = {
providerName: "OpenAI" as ServiceProvider, providerName: "OpenAI" as ServiceProvider,
temperature: 0.5, temperature: 0.5,
top_p: 1, top_p: 1,
max_completions_tokens: 4000, max_tokens: 4000,
presence_penalty: 0, presence_penalty: 0,
frequency_penalty: 0, frequency_penalty: 0,
sendMemory: true, sendMemory: true,
historyMessageCount: 4, historyMessageCount: 4,
compressMessageLengthThreshold: 1000, compressMessageLengthThreshold: 1000,
compressModel: "", compressModel: "gpt-4o-mini" as ModelType,
compressProviderName: "", compressProviderName: "OpenAI" as ServiceProvider,
enableInjectSystemPrompts: true, enableInjectSystemPrompts: true,
template: config?.template ?? DEFAULT_INPUT_TEMPLATE, template: config?.template ?? DEFAULT_INPUT_TEMPLATE,
size: "1024x1024" as DalleSize, size: "1024x1024" as DalleSize,
@@ -127,7 +127,7 @@ export const ModalConfigValidator = {
model(x: string) { model(x: string) {
return x as ModelType; return x as ModelType;
}, },
max_completions_tokens(x: number) { max_tokens(x: number) {
return limitNumber(x, 0, 512000, 1024); return limitNumber(x, 0, 512000, 1024);
}, },
presence_penalty(x: number) { presence_penalty(x: number) {
@@ -178,7 +178,7 @@ export const useAppConfig = createPersistStore(
}), }),
{ {
name: StoreKey.Config, name: StoreKey.Config,
version: 4.1, version: 4,
merge(persistedState, currentState) { merge(persistedState, currentState) {
const state = persistedState as ChatConfig | undefined; const state = persistedState as ChatConfig | undefined;
@@ -231,7 +231,7 @@ export const useAppConfig = createPersistStore(
: config?.template ?? DEFAULT_INPUT_TEMPLATE; : config?.template ?? DEFAULT_INPUT_TEMPLATE;
} }
if (version < 4.1) { if (version < 4) {
state.modelConfig.compressModel = state.modelConfig.compressModel =
DEFAULT_CONFIG.modelConfig.compressModel; DEFAULT_CONFIG.modelConfig.compressModel;
state.modelConfig.compressProviderName = state.modelConfig.compressProviderName =

View File

@@ -4,10 +4,10 @@ import { nanoid } from "nanoid";
import { createPersistStore } from "../utils/store"; import { createPersistStore } from "../utils/store";
import { getClientConfig } from "../config/client"; import { getClientConfig } from "../config/client";
import yaml from "js-yaml"; import yaml from "js-yaml";
import { adapter, getOperationId } from "../utils"; import { adapter } from "../utils";
import { useAccessStore } from "./access"; import { useAccessStore } from "./access";
const isApp = getClientConfig()?.isApp !== false; const isApp = getClientConfig()?.isApp;
export type Plugin = { export type Plugin = {
id: string; id: string;
@@ -116,7 +116,7 @@ export const FunctionToolService = {
return { return {
type: "function", type: "function",
function: { function: {
name: getOperationId(o), name: o.operationId,
description: o.description || o.summary, description: o.description || o.summary,
parameters: parameters, parameters: parameters,
}, },
@@ -124,7 +124,7 @@ export const FunctionToolService = {
}), }),
funcs: operations.reduce((s, o) => { funcs: operations.reduce((s, o) => {
// @ts-ignore // @ts-ignore
s[getOperationId(o)] = function (args) { s[o.operationId] = function (args) {
const parameters: Record<string, any> = {}; const parameters: Record<string, any> = {};
if (o.parameters instanceof Array) { if (o.parameters instanceof Array) {
o.parameters.forEach((p) => { o.parameters.forEach((p) => {
@@ -139,8 +139,8 @@ export const FunctionToolService = {
} else if (authLocation == "body") { } else if (authLocation == "body") {
args[headerName] = tokenValue; args[headerName] = tokenValue;
} }
// @ts-ignore if o.operationId is null, then using o.path and o.method // @ts-ignore
return api.client.paths[o.path][o.method]( return api.client[o.operationId](
parameters, parameters,
args, args,
api.axiosConfigDefaults, api.axiosConfigDefaults,

View File

@@ -151,7 +151,7 @@ export const usePromptStore = createPersistStore(
if (typeof window === "undefined") { if (typeof window === "undefined") {
return; return;
} }
const PROMPT_URL = "./prompts.json"; const PROMPT_URL = "./prompts.json";
type PromptList = Array<[string, string]>; type PromptList = Array<[string, string]>;

View File

@@ -3,8 +3,7 @@ import { showToast } from "./components/ui-lib";
import Locale from "./locales"; import Locale from "./locales";
import { RequestMessage } from "./client/api"; import { RequestMessage } from "./client/api";
import { ServiceProvider } from "./constant"; import { ServiceProvider } from "./constant";
// import { fetch as tauriFetch, ResponseType } from "@tauri-apps/api/http"; import { fetch as tauriFetch } from "@tauri-apps/plugin-http";
import { fetch as tauriStreamFetch } from "./utils/stream";
export function trimTopic(topic: string) { export function trimTopic(topic: string) {
// Fix an issue where double quotes still show in the Indonesian language // Fix an issue where double quotes still show in the Indonesian language
@@ -285,9 +284,6 @@ export function showPlugins(provider: ServiceProvider, model: string) {
if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) { if (provider == ServiceProvider.Anthropic && !model.includes("claude-2")) {
return true; return true;
} }
if (provider == ServiceProvider.Google && !model.includes("vision")) {
return true;
}
return false; return false;
} }
@@ -296,23 +292,23 @@ export function fetch(
options?: Record<string, unknown>, options?: Record<string, unknown>,
): Promise<any> { ): Promise<any> {
if (window.__TAURI__) { if (window.__TAURI__) {
return tauriStreamFetch(url, options); return tauriFetch(url, options);
} }
return window.fetch(url, options); return window.fetch(url, options);
} }
export function adapter(config: Record<string, unknown>) { export function adapter(config: Record<string, unknown>) {
const { baseURL, url, params, data: body, ...rest } = config; const { baseURL, url, params, ...rest } = config;
const path = baseURL ? `${baseURL}${url}` : url; const path = baseURL ? `${baseURL}${url}` : url;
const fetchUrl = params const fetchUrl = params
? `${path}?${new URLSearchParams(params as any).toString()}` ? `${path}?${new URLSearchParams(params as any).toString()}`
: path; : path;
return fetch(fetchUrl as string, { ...rest, body }).then((res) => { if (window.__TAURI__) {
const { status, headers, statusText } = res; return tauriFetch(fetchUrl as string, rest)
return res .then((res) => res.text())
.text() .then((data: any) => ({ data }));
.then((data: string) => ({ status, statusText, headers, data })); }
}); return window.fetch(fetchUrl as string, rest);
} }
export function safeLocalStorage(): { export function safeLocalStorage(): {
@@ -374,15 +370,3 @@ export function safeLocalStorage(): {
}, },
}; };
} }
export function getOperationId(operation: {
operationId?: string;
method: string;
path: string;
}) {
// pattern '^[a-zA-Z0-9_-]+$'
return (
operation?.operationId ||
`${operation.method.toUpperCase()}${operation.path.replaceAll("/", "_")}`
);
}

View File

@@ -1,19 +0,0 @@
import { sendGAEvent } from "@next/third-parties/google";
export function trackConversationGuideToCPaymentClick() {
sendGAEvent("event", "ConversationGuideToCPaymentClick", { value: 1 });
}
export function trackAuthorizationPageButtonToCPaymentClick() {
sendGAEvent("event", "AuthorizationPageButtonToCPaymentClick", { value: 1 });
}
export function trackAuthorizationPageBannerToCPaymentClick() {
sendGAEvent("event", "AuthorizationPageBannerToCPaymentClick", {
value: 1,
});
}
export function trackSettingsPageGuideToCPaymentClick() {
sendGAEvent("event", "SettingsPageGuideToCPaymentClick", { value: 1 });
}

View File

@@ -10,7 +10,7 @@ import {
fetchEventSource, fetchEventSource,
} from "@fortaine/fetch-event-source"; } from "@fortaine/fetch-event-source";
import { prettyObject } from "./format"; import { prettyObject } from "./format";
import { fetch as tauriFetch } from "./stream"; import { fetch } from "@/app/utils";
export function compressImage(file: Blob, maxSize: number): Promise<string> { export function compressImage(file: Blob, maxSize: number): Promise<string> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@@ -222,12 +222,7 @@ export function stream(
), ),
) )
.then((res) => { .then((res) => {
let content = res.data || res?.statusText; const content = JSON.stringify(res.data);
// hotfix #5614
content =
typeof content === "string"
? content
: JSON.stringify(content);
if (res.status >= 300) { if (res.status >= 300) {
return Promise.reject(content); return Promise.reject(content);
} }
@@ -242,15 +237,10 @@ export function stream(
return content; return content;
}) })
.catch((e) => { .catch((e) => {
options?.onAfterTool?.({ options?.onAfterTool?.({ ...tool, isError: true });
...tool,
isError: true,
errorMsg: e.toString(),
});
return e.toString(); return e.toString();
}) })
.then((content) => ({ .then((content) => ({
name: tool.function.name,
role: "tool", role: "tool",
content, content,
tool_call_id: tool.id, tool_call_id: tool.id,
@@ -298,7 +288,7 @@ export function stream(
REQUEST_TIMEOUT_MS, REQUEST_TIMEOUT_MS,
); );
fetchEventSource(chatPath, { fetchEventSource(chatPath, {
fetch: tauriFetch as any, fetch: fetch as any, // using tauriFetch or window.fetch
...chatPayload, ...chatPayload,
async onopen(res) { async onopen(res) {
clearTimeout(requestTimeoutId); clearTimeout(requestTimeoutId);

View File

@@ -1,107 +0,0 @@
// using tauri command to send request
// see src-tauri/src/stream.rs, and src-tauri/src/main.rs
// 1. invoke('stream_fetch', {url, method, headers, body}), get response with headers.
// 2. listen event: `stream-response` multi times to get body
type ResponseEvent = {
id: number;
payload: {
request_id: number;
status?: number;
chunk?: number[];
};
};
type StreamResponse = {
request_id: number;
status: number;
status_text: string;
headers: Record<string, string>;
};
export function fetch(url: string, options?: RequestInit): Promise<any> {
if (window.__TAURI__) {
const {
signal,
method = "GET",
headers: _headers = {},
body = [],
} = options || {};
let unlisten: Function | undefined;
let setRequestId: Function | undefined;
const requestIdPromise = new Promise((resolve) => (setRequestId = resolve));
const ts = new TransformStream();
const writer = ts.writable.getWriter();
let closed = false;
const close = () => {
if (closed) return;
closed = true;
unlisten && unlisten();
writer.ready.then(() => {
writer.close().catch((e) => console.error(e));
});
};
if (signal) {
signal.addEventListener("abort", () => close());
}
// @ts-ignore 2. listen response multi times, and write to Response.body
window.__TAURI__.event
.listen("stream-response", (e: ResponseEvent) =>
requestIdPromise.then((request_id) => {
const { request_id: rid, chunk, status } = e?.payload || {};
if (request_id != rid) {
return;
}
if (chunk) {
writer.ready.then(() => {
writer.write(new Uint8Array(chunk));
});
} else if (status === 0) {
// end of body
close();
}
}),
)
.then((u: Function) => (unlisten = u));
const headers: Record<string, string> = {
Accept: "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7",
"User-Agent": navigator.userAgent,
};
for (const item of new Headers(_headers || {})) {
headers[item[0]] = item[1];
}
return window.__TAURI__
.invoke("stream_fetch", {
method: method.toUpperCase(),
url,
headers,
// TODO FormData
body:
typeof body === "string"
? Array.from(new TextEncoder().encode(body))
: [],
})
.then((res: StreamResponse) => {
const { request_id, status, status_text: statusText, headers } = res;
setRequestId?.(request_id);
const response = new Response(ts.readable, {
status,
statusText,
headers,
});
if (status >= 300) {
setTimeout(close, 100);
}
return response;
})
.catch((e) => {
console.error("stream error", e);
throw e;
});
}
return window.fetch(url, options);
}

View File

@@ -1,21 +0,0 @@
import type { Config } from "jest";
import nextJest from "next/jest.js";
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});
// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: "v8",
testEnvironment: "jsdom",
testMatch: ["**/*.test.js", "**/*.test.ts", "**/*.test.jsx", "**/*.test.tsx"],
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/$1",
},
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config);

View File

@@ -1,2 +0,0 @@
// Learn more: https://github.com/testing-library/jest-dom
import "@testing-library/jest-dom";

View File

@@ -6,24 +6,26 @@
"mask": "npx tsx app/masks/build.ts", "mask": "npx tsx app/masks/build.ts",
"mask:watch": "npx watch \"yarn mask\" app/masks", "mask:watch": "npx watch \"yarn mask\" app/masks",
"dev": "concurrently -r \"yarn run mask:watch\" \"next dev\"", "dev": "concurrently -r \"yarn run mask:watch\" \"next dev\"",
"build": "yarn test:ci && yarn mask && cross-env BUILD_MODE=standalone next build", "build": "yarn mask && cross-env BUILD_MODE=standalone next build",
"start": "next start", "start": "next start",
"lint": "next lint", "lint": "next lint",
"export": "yarn test:ci && yarn mask && cross-env BUILD_MODE=export BUILD_APP=1 next build", "export": "yarn mask && cross-env BUILD_MODE=export BUILD_APP=1 next build",
"export:dev": "concurrently -r \"yarn mask:watch\" \"cross-env BUILD_MODE=export BUILD_APP=1 next dev\"", "export:dev": "concurrently -r \"yarn mask:watch\" \"cross-env BUILD_MODE=export BUILD_APP=1 next dev\"",
"app:dev": "concurrently -r \"yarn mask:watch\" \"yarn tauri dev\"", "app:dev": "concurrently -r \"yarn mask:watch\" \"yarn tauri dev\"",
"app:build": "yarn test:ci && yarn mask && yarn tauri build", "app:build": "yarn mask && yarn tauri build",
"ios:init": "yarn tauri ios init",
"ios:dev": "concurrently -r \"yarn mask:watch\" \"yarn tauri ios dev\"",
"ios:build": "yarn mask && yarn tauri ios build",
"prompts": "node ./scripts/fetch-prompts.mjs", "prompts": "node ./scripts/fetch-prompts.mjs",
"prepare": "husky install", "prepare": "husky install",
"proxy-dev": "sh ./scripts/init-proxy.sh && proxychains -f ./scripts/proxychains.conf yarn dev", "proxy-dev": "sh ./scripts/init-proxy.sh && proxychains -f ./scripts/proxychains.conf yarn dev"
"test": "jest --watch",
"test:ci": "jest --ci"
}, },
"dependencies": { "dependencies": {
"@fortaine/fetch-event-source": "^3.0.6", "@fortaine/fetch-event-source": "^3.0.6",
"@hello-pangea/dnd": "^16.5.0", "@hello-pangea/dnd": "^16.5.0",
"@next/third-parties": "^14.1.0", "@next/third-parties": "^14.1.0",
"@svgr/webpack": "^6.5.1", "@svgr/webpack": "^6.5.1",
"@tauri-apps/plugin-http": "^2.0.0-rc.2",
"@vercel/analytics": "^0.1.11", "@vercel/analytics": "^0.1.11",
"@vercel/speed-insights": "^1.0.2", "@vercel/speed-insights": "^1.0.2",
"axios": "^1.7.5", "axios": "^1.7.5",
@@ -33,8 +35,8 @@
"html-to-image": "^1.11.11", "html-to-image": "^1.11.11",
"idb-keyval": "^6.2.1", "idb-keyval": "^6.2.1",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"mermaid": "^10.6.1",
"markdown-to-txt": "^2.0.1", "markdown-to-txt": "^2.0.1",
"mermaid": "^10.6.1",
"nanoid": "^5.0.3", "nanoid": "^5.0.3",
"next": "^14.1.1", "next": "^14.1.1",
"node-fetch": "^3.3.1", "node-fetch": "^3.3.1",
@@ -54,11 +56,7 @@
"zustand": "^4.3.8" "zustand": "^4.3.8"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/api": "^1.6.0", "@tauri-apps/cli": "^2.0.0-rc.0",
"@tauri-apps/cli": "1.5.11",
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/react": "^16.0.0",
"@types/jest": "^29.5.12",
"@types/js-yaml": "4.0.9", "@types/js-yaml": "4.0.9",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"@types/node": "^20.11.30", "@types/node": "^20.11.30",
@@ -74,11 +72,8 @@
"eslint-plugin-prettier": "^5.1.3", "eslint-plugin-prettier": "^5.1.3",
"eslint-plugin-unused-imports": "^3.2.0", "eslint-plugin-unused-imports": "^3.2.0",
"husky": "^8.0.0", "husky": "^8.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"lint-staged": "^13.2.2", "lint-staged": "^13.2.2",
"prettier": "^3.0.2", "prettier": "^3.0.2",
"ts-node": "^10.9.2",
"tsx": "^4.16.0", "tsx": "^4.16.0",
"typescript": "5.2.2", "typescript": "5.2.2",
"watch": "^1.0.2", "watch": "^1.0.2",
@@ -88,4 +83,4 @@
"lint-staged/yaml": "^2.2.2" "lint-staged/yaml": "^2.2.2"
}, },
"packageManager": "yarn@1.22.19" "packageManager": "yarn@1.22.19"
} }

View File

@@ -1,3 +1,4 @@
# Generated by Cargo # Generated by Cargo
# will have compiled files and executables # will have compiled files and executables
/target/ /target/
/gen/

4038
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,48 +2,55 @@
name = "nextchat" name = "nextchat"
version = "0.1.0" version = "0.1.0"
description = "A cross platform app for LLM ChatBot." description = "A cross platform app for LLM ChatBot."
authors = ["Yidadaa"] authors = ["GPTsMotion Tech LLC"]
license = "mit" license = "mit"
repository = "" repository = "https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web"
default-run = "nextchat" default-run = "nextchat"
edition = "2021" edition = "2021"
rust-version = "1.60" rust-version = "1.71"
[lib]
name = "nextchat"
crate-type = ["staticlib", "cdylib", "rlib"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.5.1", features = [] } tauri-build = { version = "2.0.0-rc", features = [] }
[dependencies] [dependencies]
serde_json = "1.0" serde_json = "1.0"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.5.4", features = [ "http-all", log = "0.4"
"notification-all", tauri = { version = "2.0.0-rc.15", features = [] }
"fs-all", tauri-plugin-log = "2.0.0-rc"
"clipboard-all", tauri-plugin-clipboard-manager = "2.0.0-rc.4"
"dialog-all", tauri-plugin-dialog = "2.0.0-rc.7"
"shell-open", tauri-plugin-fs = "2.0.0-rc.5"
"updater", tauri-plugin-http = "2.0.0-rc.5"
"window-close", tauri-plugin-updater = "2.0.0-rc.3"
"window-hide", tauri-plugin-notification = "2.0.0-rc.5"
"window-maximize", tauri-plugin-shell = "2.0.0-rc.3"
"window-minimize", tauri-plugin-window-state = "2.0.0-rc.5"
"window-set-icon",
"window-set-ignore-cursor-events",
"window-set-resizable", [replace]
"window-show", # using this version from github fixed data_directory for webkitgtk
"window-start-dragging", "wry:0.43.1" = { git = "https://github.com/lloydzhou/wry", branch="webkitgtk-data_manager-directory" }
"window-unmaximize",
"window-unminimize", # Optimize for smaller binary size
] } [profile.release]
tauri-plugin-window-state = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v1" } panic = "abort" # Strip expensive panic clean-up logic
percent-encoding = "2.3.1" codegen-units = 1 # Compile crates one after another so the compiler can optimize better
reqwest = "0.11.18" lto = true # Enables link to optimizations
futures-util = "0.3.30" opt-level = "s" # Optimize for binary size
bytes = "1.7.2" strip = true # Remove debug symbols
[features] [features]
# this feature is used for production builds or when `devPath` points to the filesystem and the built-in dev server is disabled. # this feature is used for production builds or when `devPath` points to the filesystem and the built-in dev server is disabled.
# If you use cargo directly instead of tauri's cli you can use this feature flag to switch between tauri's `dev` and `build` modes. # If you use cargo directly instead of tauri's cli you can use this feature flag to switch between tauri's `dev` and `build` modes.
# DO NOT REMOVE!! # DO NOT REMOVE!!
custom-protocol = ["tauri/custom-protocol"] custom-protocol = ["tauri/custom-protocol"]

View File

@@ -0,0 +1,29 @@
{
"identifier": "main",
"description": "permissions for desktop app",
"local": true,
"windows": ["main"],
"permissions": [
"core:default",
"core:window:allow-start-dragging",
"core:window:allow-maximize",
"clipboard-manager:allow-write-text",
"fs:default",
"fs:allow-exists",
{
"identifier": "http:default",
"allow": [
{
"url": "https://*"
},
{
"url": "http://*"
}
]
},
"notification:default",
"shell:allow-open",
"window-state:allow-restore-state",
"window-state:allow-save-window-state"
]
}

24
src-tauri/src/lib.rs Normal file
View File

@@ -0,0 +1,24 @@
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_clipboard_manager::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_http::init())
.plugin(tauri_plugin_notification::init())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_window_state::Builder::default().build())
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
app.handle().plugin(tauri_plugin_updater::Builder::new().build())?;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@@ -1,12 +1,4 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod stream;
fn main() { fn main() {
tauri::Builder::default() nextchat::run()
.invoke_handler(tauri::generate_handler![stream::stream_fetch]) }
.plugin(tauri_plugin_window_state::Builder::default().build())
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View File

@@ -1,134 +0,0 @@
//
//
use std::time::Duration;
use std::error::Error;
use std::sync::atomic::{AtomicU32, Ordering};
use std::collections::HashMap;
use futures_util::{StreamExt};
use reqwest::Client;
use reqwest::header::{HeaderName, HeaderMap};
static REQUEST_COUNTER: AtomicU32 = AtomicU32::new(0);
#[derive(Debug, Clone, serde::Serialize)]
pub struct StreamResponse {
request_id: u32,
status: u16,
status_text: String,
headers: HashMap<String, String>
}
#[derive(Clone, serde::Serialize)]
pub struct EndPayload {
request_id: u32,
status: u16,
}
#[derive(Clone, serde::Serialize)]
pub struct ChunkPayload {
request_id: u32,
chunk: bytes::Bytes,
}
#[tauri::command]
pub async fn stream_fetch(
window: tauri::Window,
method: String,
url: String,
headers: HashMap<String, String>,
body: Vec<u8>,
) -> Result<StreamResponse, String> {
let event_name = "stream-response";
let request_id = REQUEST_COUNTER.fetch_add(1, Ordering::SeqCst);
let mut _headers = HeaderMap::new();
for (key, value) in &headers {
_headers.insert(key.parse::<HeaderName>().unwrap(), value.parse().unwrap());
}
// println!("method: {:?}", method);
// println!("url: {:?}", url);
// println!("headers: {:?}", headers);
// println!("headers: {:?}", _headers);
let method = method.parse::<reqwest::Method>().map_err(|err| format!("failed to parse method: {}", err))?;
let client = Client::builder()
.default_headers(_headers)
.redirect(reqwest::redirect::Policy::limited(3))
.connect_timeout(Duration::new(3, 0))
.build()
.map_err(|err| format!("failed to generate client: {}", err))?;
let mut request = client.request(
method.clone(),
url.parse::<reqwest::Url>().map_err(|err| format!("failed to parse url: {}", err))?
);
if method == reqwest::Method::POST || method == reqwest::Method::PUT || method == reqwest::Method::PATCH {
let body = bytes::Bytes::from(body);
// println!("body: {:?}", body);
request = request.body(body);
}
// println!("client: {:?}", client);
// println!("request: {:?}", request);
let response_future = request.send();
let res = response_future.await;
let response = match res {
Ok(res) => {
// get response and emit to client
let mut headers = HashMap::new();
for (name, value) in res.headers() {
headers.insert(
name.as_str().to_string(),
std::str::from_utf8(value.as_bytes()).unwrap().to_string()
);
}
let status = res.status().as_u16();
tauri::async_runtime::spawn(async move {
let mut stream = res.bytes_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => {
// println!("chunk: {:?}", bytes);
if let Err(e) = window.emit(event_name, ChunkPayload{ request_id, chunk: bytes }) {
println!("Failed to emit chunk payload: {:?}", e);
}
}
Err(err) => {
println!("Error chunk: {:?}", err);
}
}
}
if let Err(e) = window.emit(event_name, EndPayload{ request_id, status: 0 }) {
println!("Failed to emit end payload: {:?}", e);
}
});
StreamResponse {
request_id,
status,
status_text: "OK".to_string(),
headers,
}
}
Err(err) => {
println!("Error response: {:?}", err.source().expect("REASON").to_string());
StreamResponse {
request_id,
status: 599,
status_text: err.source().expect("REASON").to_string(),
headers: HashMap::new(),
}
}
};
// println!("Response: {:?}", response);
Ok(response)
}

View File

@@ -1,110 +1,30 @@
{ {
"$schema": "../node_modules/@tauri-apps/cli/schema.json", "$schema": "../node_modules/@tauri-apps/cli/schema.json",
"productName": "NextChat",
"mainBinaryName": "next-chat",
"identifier": "com.yida.chatgpt.next.web",
"version": "2.15.4",
"build": { "build": {
"beforeBuildCommand": "yarn export", "beforeBuildCommand": "yarn export",
"beforeDevCommand": "yarn export:dev", "beforeDevCommand": "yarn export:dev",
"devPath": "http://localhost:3000", "devUrl": "http://localhost:3000",
"distDir": "../out", "frontendDist": "../out"
"withGlobalTauri": true
}, },
"package": { "plugins": {
"productName": "NextChat",
"version": "2.15.4"
},
"tauri": {
"allowlist": {
"all": false,
"shell": {
"all": false,
"open": true
},
"dialog": {
"all": true,
"ask": true,
"confirm": true,
"message": true,
"open": true,
"save": true
},
"clipboard": {
"all": true,
"writeText": true,
"readText": true
},
"window": {
"all": false,
"close": true,
"hide": true,
"maximize": true,
"minimize": true,
"setIcon": true,
"setIgnoreCursorEvents": true,
"setResizable": true,
"show": true,
"startDragging": true,
"unmaximize": true,
"unminimize": true
},
"fs": {
"all": true
},
"notification": {
"all": true
},
"http": {
"all": true,
"request": true,
"scope": ["https://*", "http://*"]
}
},
"bundle": {
"active": true,
"category": "DeveloperTool",
"copyright": "2023, Zhang Yifei All Rights Reserved.",
"deb": {
"depends": []
},
"externalBin": [],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"identifier": "com.yida.chatgpt.next.web",
"longDescription": "NextChat is a cross-platform ChatGPT client, including Web/Win/Linux/OSX/PWA.",
"macOS": {
"entitlements": null,
"exceptionDomain": "",
"frameworks": [],
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "NextChat App",
"targets": "all",
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
}
},
"security": {
"csp": null,
"dangerousUseHttpScheme": true
},
"updater": { "updater": {
"active": true, "active": true,
"endpoints": [
"https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/releases/latest/download/latest.json"
],
"dialog": false, "dialog": false,
"windows": { "windows": {
"installMode": "passive" "installMode": "passive"
}, },
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERFNDE4MENFM0Y1RTZBOTQKUldTVWFsNC96b0JCM3RqM2NmMnlFTmxIaStRaEJrTHNOU2VqRVlIV1hwVURoWUdVdEc1eDcxVEYK" "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IERFNDE4MENFM0Y1RTZBOTQKUldTVWFsNC96b0JCM3RqM2NmMnlFTmxIaStRaEJrTHNOU2VqRVlIV1hwVURoWUdVdEc1eDcxVEYK",
}, "endpoints": [
"https://github.com/ChatGPTNextWeb/ChatGPT-Next-Web/releases/latest/download/latest.json"
]
}
},
"app": {
"withGlobalTauri": true,
"windows": [ "windows": [
{ {
"fullscreen": false, "fullscreen": false,
@@ -115,6 +35,28 @@
"hiddenTitle": true, "hiddenTitle": true,
"titleBarStyle": "Overlay" "titleBarStyle": "Overlay"
} }
] ],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"category": "Utility",
"copyright": "Copyright © 2024 GPTsMotion Tech LLC All Rights Reserved.",
"shortDescription": "NextChat App",
"longDescription": "Experience NextChat: Local-first, seamless, and designed for the ultimate chat experience",
"macOS": {
"signingIdentity": "-"
},
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"createUpdaterArtifacts": "v1Compatible"
} }
} }

View File

@@ -1,9 +0,0 @@
function sum(a: number, b: number) {
return a + b;
}
describe("sum module", () => {
test("adds 1 + 2 to equal 3", () => {
expect(sum(1, 2)).toBe(3);
});
});

6959
yarn.lock

File diff suppressed because it is too large Load Diff