Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
赵月辉
/
fastgpt-migrated
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Unverified
Commit
8b72dca5
authored
Mar 23, 2023
by
archer
Browse files
Options
Browse Files
Download
Plain Diff
merge dev2.0
parents
4d640685
af35e17f
Hide whitespace changes
Inline
Side-by-side
Showing
4 changed files
with
77 additions
and
37 deletions
+77
-37
src/api/fetch.ts
+4
-2
src/pages/api/chat/chatGpt.ts
+37
-14
src/pages/chat/index.tsx
+13
-2
src/service/events/bill.ts
+23
-19
No files found.
src/api/fetch.ts
View file @
8b72dca5
...
@@ -3,8 +3,9 @@ interface StreamFetchProps {
...
@@ -3,8 +3,9 @@ interface StreamFetchProps {
url
:
string
;
url
:
string
;
data
:
any
;
data
:
any
;
onMessage
:
(
text
:
string
)
=>
void
;
onMessage
:
(
text
:
string
)
=>
void
;
abortSignal
:
AbortController
;
}
}
export
const
streamFetch
=
({
url
,
data
,
onMessage
}:
StreamFetchProps
)
=>
export
const
streamFetch
=
({
url
,
data
,
onMessage
,
abortSignal
}:
StreamFetchProps
)
=>
new
Promise
(
async
(
resolve
,
reject
)
=>
{
new
Promise
(
async
(
resolve
,
reject
)
=>
{
try
{
try
{
const
res
=
await
fetch
(
url
,
{
const
res
=
await
fetch
(
url
,
{
...
@@ -13,7 +14,8 @@ export const streamFetch = ({ url, data, onMessage }: StreamFetchProps) =>
...
@@ -13,7 +14,8 @@ export const streamFetch = ({ url, data, onMessage }: StreamFetchProps) =>
'Content-Type'
:
'application/json'
,
'Content-Type'
:
'application/json'
,
Authorization
:
getToken
()
||
''
Authorization
:
getToken
()
||
''
},
},
body
:
JSON
.
stringify
(
data
)
body
:
JSON
.
stringify
(
data
),
signal
:
abortSignal
.
signal
});
});
const
reader
=
res
.
body
?.
getReader
();
const
reader
=
res
.
body
?.
getReader
();
if
(
!
reader
)
return
;
if
(
!
reader
)
return
;
...
...
src/pages/api/chat/chatGpt.ts
View file @
8b72dca5
...
@@ -13,13 +13,26 @@ import { pushBill } from '@/service/events/bill';
...
@@ -13,13 +13,26 @@ import { pushBill } from '@/service/events/bill';
/* 发送提示词 */
/* 发送提示词 */
export
default
async
function
handler
(
req
:
NextApiRequest
,
res
:
NextApiResponse
)
{
export
default
async
function
handler
(
req
:
NextApiRequest
,
res
:
NextApiResponse
)
{
const
{
chatId
,
prompt
}
=
req
.
body
as
{
let
step
=
0
;
// step=1时,表示开始了流响应
prompt
:
ChatItemType
;
const
stream
=
new
PassThrough
();
chatId
:
string
;
stream
.
on
(
'error'
,
()
=>
{
};
console
.
log
(
'error: '
,
'stream error'
);
const
{
authorization
}
=
req
.
headers
;
stream
.
destroy
();
});
res
.
on
(
'close'
,
()
=>
{
stream
.
destroy
();
});
res
.
on
(
'error'
,
()
=>
{
console
.
log
(
'error: '
,
'request error'
);
stream
.
destroy
();
});
try
{
try
{
const
{
chatId
,
prompt
}
=
req
.
body
as
{
prompt
:
ChatItemType
;
chatId
:
string
;
};
const
{
authorization
}
=
req
.
headers
;
if
(
!
chatId
||
!
prompt
)
{
if
(
!
chatId
||
!
prompt
)
{
throw
new
Error
(
'缺少参数'
);
throw
new
Error
(
'缺少参数'
);
}
}
...
@@ -92,10 +105,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
...
@@ -92,10 +105,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res
.
setHeader
(
'Access-Control-Allow-Origin'
,
'*'
);
res
.
setHeader
(
'Access-Control-Allow-Origin'
,
'*'
);
res
.
setHeader
(
'X-Accel-Buffering'
,
'no'
);
res
.
setHeader
(
'X-Accel-Buffering'
,
'no'
);
res
.
setHeader
(
'Cache-Control'
,
'no-cache, no-transform'
);
res
.
setHeader
(
'Cache-Control'
,
'no-cache, no-transform'
);
step
=
1
;
let
responseContent
=
''
;
let
responseContent
=
''
;
const
pass
=
new
PassThrough
();
stream
.
pipe
(
res
);
pass
.
pipe
(
res
);
const
onParse
=
async
(
event
:
ParsedEvent
|
ReconnectInterval
)
=>
{
const
onParse
=
async
(
event
:
ParsedEvent
|
ReconnectInterval
)
=>
{
if
(
event
.
type
!==
'event'
)
return
;
if
(
event
.
type
!==
'event'
)
return
;
...
@@ -107,7 +120,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
...
@@ -107,7 +120,7 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
if
(
!
content
)
return
;
if
(
!
content
)
return
;
responseContent
+=
content
;
responseContent
+=
content
;
// console.log('content:', content)
// console.log('content:', content)
pass
.
push
(
content
.
replace
(
/
\n
/g
,
'<br/>'
));
stream
.
push
(
content
.
replace
(
/
\n
/g
,
'<br/>'
));
}
catch
(
error
)
{
}
catch
(
error
)
{
error
;
error
;
}
}
...
@@ -116,13 +129,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
...
@@ -116,13 +129,17 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
const
decoder
=
new
TextDecoder
();
const
decoder
=
new
TextDecoder
();
try
{
try
{
for
await
(
const
chunk
of
chatResponse
.
data
as
any
)
{
for
await
(
const
chunk
of
chatResponse
.
data
as
any
)
{
if
(
stream
.
destroyed
)
{
// 流被中断了,直接忽略后面的内容
break
;
}
const
parser
=
createParser
(
onParse
);
const
parser
=
createParser
(
onParse
);
parser
.
feed
(
decoder
.
decode
(
chunk
));
parser
.
feed
(
decoder
.
decode
(
chunk
));
}
}
}
catch
(
error
)
{
}
catch
(
error
)
{
console
.
log
(
'pipe error'
,
error
);
console
.
log
(
'pipe error'
,
error
);
}
}
pass
.
push
(
null
);
stream
.
push
(
null
);
const
promptsLen
=
formatPrompts
.
reduce
((
sum
,
item
)
=>
sum
+
item
.
content
.
length
,
0
);
const
promptsLen
=
formatPrompts
.
reduce
((
sum
,
item
)
=>
sum
+
item
.
content
.
length
,
0
);
console
.
log
(
`responseLen:
${
responseContent
.
length
}
`
,
`promptLen:
${
promptsLen
}
`
);
console
.
log
(
`responseLen:
${
responseContent
.
length
}
`
,
`promptLen:
${
promptsLen
}
`
);
...
@@ -135,10 +152,16 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
...
@@ -135,10 +152,16 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
textLen
:
promptsLen
+
responseContent
.
length
textLen
:
promptsLen
+
responseContent
.
length
});
});
}
catch
(
err
:
any
)
{
}
catch
(
err
:
any
)
{
res
.
status
(
500
);
if
(
step
===
1
)
{
jsonRes
(
res
,
{
console
.
log
(
'error,结束'
);
code
:
500
,
// 直接结束流
error
:
err
stream
.
destroy
();
});
}
else
{
res
.
status
(
500
);
jsonRes
(
res
,
{
code
:
500
,
error
:
err
});
}
}
}
}
}
src/pages/chat/index.tsx
View file @
8b72dca5
import
React
,
{
useCallback
,
useState
,
useRef
,
useMemo
}
from
'react'
;
import
React
,
{
useCallback
,
useState
,
useRef
,
useMemo
,
useEffect
}
from
'react'
;
import
{
useRouter
}
from
'next/router'
;
import
{
useRouter
}
from
'next/router'
;
import
Image
from
'next/image'
;
import
Image
from
'next/image'
;
import
{
import
{
...
@@ -88,6 +88,16 @@ const Chat = ({ chatId }: { chatId: string }) => {
...
@@ -88,6 +88,16 @@ const Chat = ({ chatId }: { chatId: string }) => {
},
[
chatData
]);
},
[
chatData
]);
const
{
pushChatHistory
}
=
useChatStore
();
const
{
pushChatHistory
}
=
useChatStore
();
// 中断请求
const
controller
=
useRef
(
new
AbortController
());
useEffect
(()
=>
{
controller
.
current
=
new
AbortController
();
return
()
=>
{
console
.
log
(
'close========'
);
// eslint-disable-next-line react-hooks/exhaustive-deps
controller
.
current
?.
abort
();
};
},
[
chatId
]);
// 滚动到底部
// 滚动到底部
const
scrollToBottom
=
useCallback
(()
=>
{
const
scrollToBottom
=
useCallback
(()
=>
{
...
@@ -212,7 +222,8 @@ const Chat = ({ chatId }: { chatId: string }) => {
...
@@ -212,7 +222,8 @@ const Chat = ({ chatId }: { chatId: string }) => {
};
};
})
})
}));
}));
}
},
abortSignal
:
controller
.
current
});
});
// 保存对话信息
// 保存对话信息
...
...
src/service/events/bill.ts
View file @
8b72dca5
...
@@ -12,30 +12,34 @@ export const pushBill = async ({
...
@@ -12,30 +12,34 @@ export const pushBill = async ({
chatId
:
string
;
chatId
:
string
;
textLen
:
number
;
textLen
:
number
;
})
=>
{
})
=>
{
await
connectToDatabase
();
try
{
await
connectToDatabase
();
const
modelItem
=
ModelList
.
find
((
item
)
=>
item
.
model
===
modelName
);
const
modelItem
=
ModelList
.
find
((
item
)
=>
item
.
model
===
modelName
);
if
(
!
modelItem
)
return
;
if
(
!
modelItem
)
return
;
const
price
=
modelItem
.
price
*
textLen
;
const
price
=
modelItem
.
price
*
textLen
;
let
billId
;
let
billId
;
try
{
try
{
// 插入 Bill 记录
// 插入 Bill 记录
const
res
=
await
Bill
.
create
({
const
res
=
await
Bill
.
create
({
userId
,
userId
,
chatId
,
chatId
,
textLen
,
textLen
,
price
price
});
});
billId
=
res
.
_id
;
billId
=
res
.
_id
;
// 扣费
// 扣费
await
User
.
findByIdAndUpdate
(
userId
,
{
await
User
.
findByIdAndUpdate
(
userId
,
{
$inc
:
{
balance
:
-
price
}
$inc
:
{
balance
:
-
price
}
});
});
}
catch
(
error
)
{
billId
&&
Bill
.
findByIdAndDelete
(
billId
);
}
}
catch
(
error
)
{
}
catch
(
error
)
{
billId
&&
Bill
.
findByIdAndDelete
(
billId
);
console
.
log
(
error
);
}
}
};
};
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment