|
1 | 1 | import type { ClientOptions } from 'openai' |
2 | 2 | import type { RequestInit } from 'undici' |
3 | | -import type { AuditConfig, Config, KeyConfig, UserInfo } from '../storage/model' |
| 3 | +import type { AuditConfig, Config, KeyConfig, SearchResult, UserInfo } from '../storage/model' |
4 | 4 | import type { TextAuditService } from '../utils/textAudit' |
5 | 5 | import type { ChatMessage, RequestOptions } from './types' |
6 | 6 | import { tavily } from '@tavily/core' |
@@ -129,23 +129,42 @@ async function chatReplyProcess(options: RequestOptions) { |
129 | 129 | if (searchQuery) { |
130 | 130 | await updateChatSearchQuery(messageId, searchQuery) |
131 | 131 |
|
| 132 | + process?.({ |
| 133 | + searchQuery, |
| 134 | + }) |
| 135 | + |
132 | 136 | const tvly = tavily({ apiKey: searchConfig.options?.apiKey }) |
133 | 137 | const response = await tvly.search( |
134 | 138 | searchQuery, |
135 | 139 | { |
136 | 140 | includeRawContent: true, |
137 | | - timeout: 300, |
| 141 | + // 0 <= x <= 20 https://docs.tavily.com/documentation/api-reference/endpoint/search#body-max-results |
| 142 | + maxResults: 20, |
| 143 | + // Max 120s, default to 60 https://github.com/tavily-ai/tavily-js/blob/de69e479c5d3f6c5d443465fa2c29407c0d3515d/src/search.ts#L118 |
| 144 | + timeout: 120, |
138 | 145 | }, |
139 | 146 | ) |
140 | 147 |
|
141 | | - const searchResult = JSON.stringify(response) |
142 | | - await updateChatSearchResult(messageId, searchResult) |
| 148 | + const searchResults = response.results as SearchResult[] |
| 149 | + const searchUsageTime = response.responseTime |
| 150 | + |
| 151 | + await updateChatSearchResult(messageId, searchResults, searchUsageTime) |
| 152 | + |
| 153 | + process?.({ |
| 154 | + searchResults, |
| 155 | + searchUsageTime, |
| 156 | + }) |
| 157 | + |
| 158 | + let searchResultContent = JSON.stringify(searchResults) |
| 159 | + // remove base64 image content |
| 160 | + const base64Pattern = /data:image\/[a-zA-Z0-9+.-]+;base64,[A-Za-z0-9+/=]+/g |
| 161 | + searchResultContent = searchResultContent.replace(base64Pattern, '') |
143 | 162 |
|
144 | 163 | messages.push({ |
145 | 164 | role: 'user', |
146 | 165 | content: `Additional information from web searche engine. |
147 | 166 | search query: <search_query>${searchQuery}</search_query> |
148 | | -search result: <search_result>${searchResult}</search_result>`, |
| 167 | +search result: <search_result>${searchResultContent}</search_result>`, |
149 | 168 | }) |
150 | 169 |
|
151 | 170 | messages[0].content = renderSystemMessage(searchConfig.systemMessageWithSearchResult, dayjs().format('YYYY-MM-DD HH:mm:ss')) |
|
0 commit comments