search.ts 4.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * The model-facing `web_search` tool: discover current information on the web.
  3. * Execution goes through `ctx.web` — this module owns only the model-facing
  4. * schema, argument validation, the result-count bound, and result formatting,
  5. * never provider selection or network access.
  6. */
  7. import type { Context } from 'cordis'
  8. import { defineTool } from '@deepseek-ai/dsh-tools'
  9. import type { GenericCallView } from '@deepseek-ai/dsh-tools'
  10. import type { ContentBlock } from '@deepseek-ai/dsh-llm'
  11. import type { WebSearchResult } from '@deepseek-ai/dsh-web'
  12. import type {} from '@deepseek-ai/dsh-system-prompt'
  13. /**
  14. * Default upper bound on returned sources. Owned by the consumer (not the
  15. * provider or model), mirroring `dsh-tool-fs`'s `READ_LIMIT`/`GREP_LIMIT`. The
  16. * model just asks a question; the product controls how much context returns.
  17. * The default `8` aligns with OpenCode's Exa default.
  18. */
  19. export const WEB_SEARCH_MAX_RESULTS = 8
  20. /** Validate value constraints the schema DSL can't express. */
  21. export function parseSearchArgs(args: { query: string }): { query: string } {
  22. if (args.query.trim().length === 0) throw new Error('query must be a non-empty string')
  23. return { query: args.query }
  24. }
  25. /** Display label for a source: its title, else its hostname. */
  26. function sourceLabel(url: string, title: string | undefined): string {
  27. if (title !== undefined && title.length > 0) return title
  28. try {
  29. return new URL(url).hostname
  30. } catch {
  31. // A provider should return a valid URL, but never let a malformed one throw
  32. // out of pure formatting — fall back to the raw string.
  33. return url
  34. }
  35. }
  36. /** Format a search result as one model-facing text block. */
  37. export function formatSearchOutput(result: WebSearchResult): string {
  38. const parts: string[] = []
  39. if (result.content !== undefined && result.content.length > 0) parts.push(result.content)
  40. if (result.sources.length > 0) {
  41. const lines = result.sources.map((source) => {
  42. const label = sourceLabel(source.url, source.title)
  43. const meta: string[] = []
  44. if (source.snippet !== undefined && source.snippet.length > 0) meta.push(source.snippet)
  45. if (source.publishedAt !== undefined && source.publishedAt.length > 0) meta.push(`(${source.publishedAt})`)
  46. const suffix = meta.length > 0 ? ` — ${meta.join(' ')}` : ''
  47. return `- [${label}](${source.url})${suffix}`
  48. })
  49. parts.push(`Sources:\n${lines.join('\n')}`)
  50. } else if (result.content === undefined || result.content.length === 0) {
  51. parts.push('No results found.')
  52. }
  53. if (result.truncated) parts.push(`(Showing the first ${result.sources.length} sources. Refine the query for more.)`)
  54. parts.push('Cite the relevant URLs above as markdown links in your answer.')
  55. return parts.join('\n\n')
  56. }
  57. /** Pending-call presentation: a search card titled by the query. */
  58. export function presentSearchCall(args: { query: string }): GenericCallView {
  59. return { card: 'generic', title: args.query, kind: 'search', rawInput: args.query }
  60. }
  61. /** Register the `web_search` tool and its system-prompt guidance. */
  62. export function applyWebSearchTool(ctx: Context): void {
  63. ctx.systemPrompt.section({
  64. name: 'tool:web_search',
  65. order: 110,
  66. text: 'Use the web_search tool to discover current information on the web. It returns an optional answer plus a list of source URLs. Follow up with web_fetch when you need the full content of a specific result, and cite the relevant URLs as markdown links.',
  67. })
  68. ctx.tools.register(defineTool({
  69. name: 'web_search',
  70. description: 'Search the web for current information. Returns an optional summary answer and a list of source URLs.',
  71. parameters: {
  72. query: { type: 'string', required: true, description: 'The search query.' },
  73. },
  74. async execute(args, exec): Promise<ContentBlock[]> {
  75. const input = parseSearchArgs(args)
  76. const result = await ctx.web.search(
  77. { query: input.query, maxResults: WEB_SEARCH_MAX_RESULTS },
  78. exec.signal ? { signal: exec.signal } : undefined,
  79. )
  80. return [{ type: 'text', text: formatSearchOutput(result) }]
  81. },
  82. presentCall: presentSearchCall,
  83. }))
  84. }