perplexity.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from 'cordis'
  3. import WebService from '@deepseek-ai/dsh-web'
  4. import {
  5. PerplexitySearchProvider,
  6. mapPerplexityResponse,
  7. PERPLEXITY_PROVIDER_ID,
  8. } from '@deepseek-ai/dsh-web-search-perplexity'
  9. import * as perplexityPlugin from '@deepseek-ai/dsh-web-search-perplexity'
  10. const options = { apiKey: 'pplx-key', baseURL: 'https://api.perplexity.test', model: 'sonar', maxTokens: 1024 }
  11. function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
  12. return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init })
  13. }
  14. afterEach(() => {
  15. vi.unstubAllGlobals()
  16. })
  17. describe('Perplexity response mapping', () => {
  18. it('maps the answer and prefers structured search_results', () => {
  19. const result = mapPerplexityResponse('q', {
  20. choices: [{ message: { content: 'the answer' } }],
  21. search_results: [
  22. { url: 'https://a.test', title: 'A', snippet: 'snip', date: '2026-02-02' },
  23. { url: 'https://b.test' },
  24. ],
  25. citations: ['https://ignored.test'],
  26. })
  27. expect(result).toEqual({
  28. providerId: PERPLEXITY_PROVIDER_ID,
  29. query: 'q',
  30. content: 'the answer',
  31. sources: [
  32. { url: 'https://a.test', title: 'A', snippet: 'snip', publishedAt: '2026-02-02' },
  33. { url: 'https://b.test' },
  34. ],
  35. truncated: false,
  36. })
  37. })
  38. it('falls back to URL-only citations when search_results is absent', () => {
  39. const result = mapPerplexityResponse('q', {
  40. choices: [{ message: { content: 'answer' } }],
  41. citations: ['https://a.test', 'https://b.test'],
  42. })
  43. expect(result.sources).toEqual([{ url: 'https://a.test' }, { url: 'https://b.test' }])
  44. })
  45. it('omits content when the answer is empty or missing', () => {
  46. expect(mapPerplexityResponse('q', { citations: [] }).content).toBeUndefined()
  47. expect(mapPerplexityResponse('q', { choices: [{ message: { content: '' } }] }).content).toBeUndefined()
  48. expect(mapPerplexityResponse('q', { choices: [{ message: { content: null } }] }).content).toBeUndefined()
  49. })
  50. it('omits null/empty optional source fields', () => {
  51. const result = mapPerplexityResponse('q', {
  52. search_results: [{ url: 'https://a.test', title: null, snippet: '', date: null }],
  53. })
  54. expect(result.sources).toEqual([{ url: 'https://a.test' }])
  55. })
  56. it('yields no sources when neither search_results nor citations are present', () => {
  57. expect(mapPerplexityResponse('q', { choices: [{ message: { content: 'a' } }] }).sources).toEqual([])
  58. })
  59. })
  60. describe('PerplexitySearchProvider status', () => {
  61. it('is unavailable without a key', () => {
  62. expect(new PerplexitySearchProvider({ ...options, apiKey: '' }).status())
  63. .toEqual({ available: false, reason: 'missing-credential' })
  64. })
  65. it('is available with a key', () => {
  66. expect(new PerplexitySearchProvider(options).status()).toEqual({ available: true })
  67. })
  68. it('is misconfigured when the base URL is unparseable', () => {
  69. expect(new PerplexitySearchProvider({ ...options, baseURL: 'not a url' }).status())
  70. .toEqual({ available: false, reason: 'misconfigured' })
  71. })
  72. it('is misconfigured when maxTokens is not a positive integer', () => {
  73. expect(new PerplexitySearchProvider({ ...options, maxTokens: 0 }).status())
  74. .toEqual({ available: false, reason: 'misconfigured' })
  75. expect(new PerplexitySearchProvider({ ...options, maxTokens: 1.5 }).status())
  76. .toEqual({ available: false, reason: 'misconfigured' })
  77. })
  78. })
  79. describe('PerplexitySearchProvider request mapping', () => {
  80. it('sends a chat-completions request with the query, model and max_tokens', async () => {
  81. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  82. vi.stubGlobal('fetch', fetchMock)
  83. await new PerplexitySearchProvider(options).search({ query: 'hello' })
  84. const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  85. expect(url).toBe('https://api.perplexity.test/chat/completions')
  86. expect((init.headers as Record<string, string>)['authorization']).toBe('Bearer pplx-key')
  87. expect(JSON.parse(init.body as string)).toEqual({ model: 'sonar', max_tokens: 1024, messages: [{ role: 'user', content: 'hello' }] })
  88. })
  89. it('sends search_recency_filter when configured, and omits it otherwise', async () => {
  90. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  91. vi.stubGlobal('fetch', fetchMock)
  92. await new PerplexitySearchProvider({ ...options, searchRecency: 'week' }).search({ query: 'q' })
  93. expect(JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string)).toMatchObject({ search_recency_filter: 'week' })
  94. await new PerplexitySearchProvider(options).search({ query: 'q' })
  95. expect(JSON.parse((fetchMock.mock.calls[1] as unknown as [string, RequestInit])[1].body as string)).not.toHaveProperty('search_recency_filter')
  96. })
  97. it('forwards the abort signal', async () => {
  98. const fetchMock = vi.fn(async () => jsonResponse({ citations: [] }))
  99. vi.stubGlobal('fetch', fetchMock)
  100. const controller = new AbortController()
  101. await new PerplexitySearchProvider(options).search({ query: 'q' }, { signal: controller.signal })
  102. const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  103. expect(init.signal).toBe(controller.signal)
  104. })
  105. })
  106. describe('PerplexitySearchProvider error handling', () => {
  107. it('maps an HTTP error to WEB_PROVIDER_ERROR with the provider message', async () => {
  108. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'rate limited' } }, { status: 429 })))
  109. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  110. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', message: 'rate limited' }))
  111. })
  112. it('handles a string-form error body', async () => {
  113. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'bad request' }, { status: 400 })))
  114. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  115. .rejects.toThrow(expect.objectContaining({ message: 'bad request' }))
  116. })
  117. it('maps a well-formed body of the wrong shape to WEB_PROVIDER_ERROR, not a raw TypeError', async () => {
  118. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ search_results: null }, { status: 200 })))
  119. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  120. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
  121. })
  122. it('keeps a status-line message when the error body is not JSON', async () => {
  123. vi.stubGlobal('fetch', vi.fn(async () => new Response('upstream error', { status: 503 })))
  124. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  125. .rejects.toThrow(expect.objectContaining({ message: 'Perplexity API error (HTTP 503)' }))
  126. })
  127. it('keeps the status-line message when the JSON error body carries no detail', async () => {
  128. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 500 })))
  129. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  130. .rejects.toThrow(expect.objectContaining({ message: 'Perplexity API error (HTTP 500)' }))
  131. })
  132. it('maps an abort to WEB_ABORTED', async () => {
  133. vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new DOMException('aborted', 'AbortError'))))
  134. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  135. .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
  136. })
  137. it('maps an unparseable success body to WEB_PROVIDER_ERROR', async () => {
  138. vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })))
  139. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  140. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
  141. })
  142. it('surfaces an abort during success-body parse as WEB_ABORTED, not provider error', async () => {
  143. const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: true, status: 200 }
  144. vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response))
  145. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  146. .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
  147. })
  148. it('surfaces an abort during error-body parse as WEB_ABORTED', async () => {
  149. const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: false, status: 500 }
  150. vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response))
  151. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  152. .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
  153. })
  154. it('maps a network failure to WEB_PROVIDER_ERROR', async () => {
  155. vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused'))))
  156. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  157. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
  158. })
  159. })
  160. describe('web-search-perplexity plugin registration', () => {
  161. it('registers the provider into ctx.web (HMR-safe)', async () => {
  162. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] })))
  163. const ctx = new Context()
  164. await ctx.plugin(WebService, { searchProvider: PERPLEXITY_PROVIDER_ID })
  165. const fiber = await ctx.plugin(perplexityPlugin, { apiKey: 'pplx-key' })
  166. await expect(ctx.web.search({ query: 'q' })).resolves.toMatchObject({ providerId: PERPLEXITY_PROVIDER_ID })
  167. await fiber.dispose()
  168. await expect(ctx.web.search({ query: 'q' }))
  169. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_CONFIGURED_MISSING' }))
  170. })
  171. it('has no default export (namespace plugin export shape)', () => {
  172. expect('default' in perplexityPlugin).toBe(false)
  173. })
  174. it('threads maxTokens and searchRecency config into the request', async () => {
  175. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  176. vi.stubGlobal('fetch', fetchMock)
  177. const ctx = new Context()
  178. await ctx.plugin(WebService, { searchProvider: PERPLEXITY_PROVIDER_ID })
  179. const fiber = await ctx.plugin(perplexityPlugin, { apiKey: 'pplx-key', maxTokens: 256, searchRecency: 'month' })
  180. await ctx.web.search({ query: 'q' })
  181. const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  182. expect(JSON.parse(init.body as string)).toMatchObject({ max_tokens: 256, search_recency_filter: 'month' })
  183. await fiber.dispose()
  184. })
  185. it('falls back to env key and defaults for base URL and model when config omits them', async () => {
  186. const prev = process.env.PERPLEXITY_API_KEY
  187. process.env.PERPLEXITY_API_KEY = 'env-key'
  188. try {
  189. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  190. vi.stubGlobal('fetch', fetchMock)
  191. const ctx = new Context()
  192. await ctx.plugin(WebService, { searchProvider: PERPLEXITY_PROVIDER_ID })
  193. const fiber = await ctx.plugin(perplexityPlugin, {})
  194. await ctx.web.search({ query: 'q' })
  195. const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  196. expect(url).toBe('https://api.perplexity.ai/chat/completions')
  197. expect(JSON.parse(init.body as string)).toMatchObject({ model: 'sonar' })
  198. await fiber.dispose()
  199. } finally {
  200. if (prev === undefined) delete process.env.PERPLEXITY_API_KEY
  201. else process.env.PERPLEXITY_API_KEY = prev
  202. }
  203. })
  204. it('is unavailable when neither config nor env supplies a key', async () => {
  205. const prev = process.env.PERPLEXITY_API_KEY
  206. delete process.env.PERPLEXITY_API_KEY
  207. try {
  208. const ctx = new Context()
  209. await ctx.plugin(WebService, { searchProvider: PERPLEXITY_PROVIDER_ID })
  210. await ctx.plugin(perplexityPlugin, {})
  211. await expect(ctx.web.search({ query: 'q' }))
  212. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_CONFIGURED_UNAVAILABLE' }))
  213. } finally {
  214. if (prev !== undefined) process.env.PERPLEXITY_API_KEY = prev
  215. }
  216. })
  217. })