perplexity.spec.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. import { afterEach, describe, expect, it, vi } from 'vitest'
  2. import { Context } from '@deepseek-ai/cordis'
  3. import WebRuntime 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).toMatchObject({ method: 'POST', redirect: 'error' })
  81. expect((init.headers as Record<string, string>)['authorization']).toBe('Bearer pplx-key')
  82. expect(JSON.parse(init.body as string)).toEqual({ model: 'sonar', max_tokens: 1024, messages: [{ role: 'user', content: 'hello' }] })
  83. })
  84. it('sends search_recency_filter when configured, and omits it otherwise', async () => {
  85. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  86. vi.stubGlobal('fetch', fetchMock)
  87. await new PerplexitySearchProvider({ ...options, searchRecency: 'week' }).search({ query: 'q' })
  88. expect(JSON.parse((fetchMock.mock.calls[0] as unknown as [string, RequestInit])[1].body as string)).toMatchObject({ search_recency_filter: 'week' })
  89. await new PerplexitySearchProvider(options).search({ query: 'q' })
  90. expect(JSON.parse((fetchMock.mock.calls[1] as unknown as [string, RequestInit])[1].body as string)).not.toHaveProperty('search_recency_filter')
  91. })
  92. it('forwards the abort signal', async () => {
  93. const fetchMock = vi.fn(async () => jsonResponse({ citations: [] }))
  94. vi.stubGlobal('fetch', fetchMock)
  95. const controller = new AbortController()
  96. await new PerplexitySearchProvider(options).search({ query: 'q' }, controller.signal)
  97. const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  98. expect(init.signal).toBe(controller.signal)
  99. })
  100. })
  101. describe('PerplexitySearchProvider error handling', () => {
  102. it('maps an HTTP error to WEB_PROVIDER_ERROR with the provider message', async () => {
  103. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: { message: 'rate limited' } }, { status: 429 })))
  104. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  105. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', message: 'rate limited' }))
  106. })
  107. it('handles a string-form error body', async () => {
  108. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'bad request' }, { status: 400 })))
  109. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  110. .rejects.toThrow(expect.objectContaining({ message: 'bad request' }))
  111. })
  112. it('maps a well-formed body of the wrong shape to WEB_PROVIDER_ERROR, not a raw TypeError', async () => {
  113. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ search_results: null }, { status: 200 })))
  114. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  115. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
  116. })
  117. it('keeps a status-line message when the error body is not JSON', async () => {
  118. vi.stubGlobal('fetch', vi.fn(async () => new Response('upstream error', { status: 503 })))
  119. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  120. .rejects.toThrow(expect.objectContaining({ message: 'Perplexity API error (HTTP 503)' }))
  121. })
  122. it('keeps the status-line message when the JSON error body carries no detail', async () => {
  123. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({}, { status: 500 })))
  124. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  125. .rejects.toThrow(expect.objectContaining({ message: 'Perplexity API error (HTTP 500)' }))
  126. })
  127. it('maps an abort to WEB_ABORTED', async () => {
  128. vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new DOMException('aborted', 'AbortError'))))
  129. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  130. .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
  131. })
  132. it('maps an unparseable success body to WEB_PROVIDER_ERROR', async () => {
  133. vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })))
  134. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  135. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
  136. })
  137. it('surfaces an abort during success-body parse as WEB_ABORTED, not provider error', async () => {
  138. const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: true, status: 200 }
  139. vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response))
  140. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  141. .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
  142. })
  143. it('surfaces an abort during error-body parse as WEB_ABORTED', async () => {
  144. const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: false, status: 500 }
  145. vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response))
  146. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  147. .rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
  148. })
  149. it('maps a network failure to WEB_PROVIDER_ERROR', async () => {
  150. vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused'))))
  151. await expect(new PerplexitySearchProvider(options).search({ query: 'q' }))
  152. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
  153. })
  154. })
  155. describe('web-search-perplexity plugin registration', () => {
  156. it('registers the provider into ctx.web (HMR-safe)', async () => {
  157. vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] })))
  158. const ctx = new Context()
  159. await ctx.plugin(WebRuntime, { searchProvider: PERPLEXITY_PROVIDER_ID })
  160. const fiber = await ctx.plugin(perplexityPlugin, { apiKey: 'pplx-key' })
  161. await expect(ctx.web.search({ query: 'q' })).resolves.toMatchObject({ content: 'a', sources: [] })
  162. await fiber.dispose()
  163. await expect(ctx.web.search({ query: 'q' }))
  164. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_CONFIGURED_MISSING' }))
  165. })
  166. it('has no default export (namespace plugin export shape)', () => {
  167. expect('default' in perplexityPlugin).toBe(false)
  168. })
  169. it('threads maxTokens and searchRecency config into the request', async () => {
  170. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  171. vi.stubGlobal('fetch', fetchMock)
  172. const ctx = new Context()
  173. await ctx.plugin(WebRuntime, { searchProvider: PERPLEXITY_PROVIDER_ID })
  174. const fiber = await ctx.plugin(perplexityPlugin, { apiKey: 'pplx-key', maxTokens: 256, searchRecency: 'month' })
  175. await ctx.web.search({ query: 'q' })
  176. const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  177. expect(JSON.parse(init.body as string)).toMatchObject({ max_tokens: 256, search_recency_filter: 'month' })
  178. await fiber.dispose()
  179. })
  180. it('falls back to env key and defaults for base URL and model when config omits them', async () => {
  181. const prev = process.env.PERPLEXITY_API_KEY
  182. process.env.PERPLEXITY_API_KEY = 'env-key'
  183. try {
  184. const fetchMock = vi.fn(async () => jsonResponse({ choices: [{ message: { content: 'a' } }], citations: [] }))
  185. vi.stubGlobal('fetch', fetchMock)
  186. const ctx = new Context()
  187. await ctx.plugin(WebRuntime, { searchProvider: PERPLEXITY_PROVIDER_ID })
  188. const fiber = await ctx.plugin(perplexityPlugin, {})
  189. await ctx.web.search({ query: 'q' })
  190. const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
  191. expect(url).toBe('https://api.perplexity.ai/chat/completions')
  192. expect(JSON.parse(init.body as string)).toMatchObject({ model: 'sonar' })
  193. await fiber.dispose()
  194. } finally {
  195. if (prev === undefined) delete process.env.PERPLEXITY_API_KEY
  196. else process.env.PERPLEXITY_API_KEY = prev
  197. }
  198. })
  199. it('is unavailable when neither config nor env supplies a key', async () => {
  200. const prev = process.env.PERPLEXITY_API_KEY
  201. delete process.env.PERPLEXITY_API_KEY
  202. try {
  203. const ctx = new Context()
  204. await ctx.plugin(WebRuntime, { searchProvider: PERPLEXITY_PROVIDER_ID })
  205. await ctx.plugin(perplexityPlugin, {})
  206. await expect(ctx.web.search({ query: 'q' }))
  207. .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_CONFIGURED_UNAVAILABLE' }))
  208. } finally {
  209. if (prev !== undefined) process.env.PERPLEXITY_API_KEY = prev
  210. }
  211. })
  212. })