perplexity.spec.ts 12 KB

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