sema-tavily 0.1.0

Search the web and extract page content through the Tavily API with typed errors

Source

package.sema

94 lines 6977de13194e
File details

Source stored with sema-tavily 0.1.0. Line links refer to these exact bytes.

SHA-256 6977de13194efb747444e609e9d6ba4518076c694b28dd8a54ee26ec16489ed0

1;; sema-tavily — Tavily web search and content extraction client
2;;
3;; A client is a plain map built by (tavily/client ...) and passed as the first
4;; argument to every call. Requests and responses are plain maps; bodies are
5;; JSON-decoded into keyword-keyed maps. Non-2xx statuses raise an error
6;; carrying method, path, status, and the API's own error message.
7;; (tavily/request ...) is the raw escape hatch the wrappers are built on.
8
9(module sema-tavily
10  (export tavily/client
11          tavily/request
12          tavily/search
13          tavily/extract)
14
15  ;; -------------------------------------------------------------------------
16  ;; Client
17  ;; -------------------------------------------------------------------------
18
19  (define (tavily/client . opts)
20    "Build a Tavily API client map. Options: :api-key (default: TAVILY_API_KEY env var), :base-url (default \"https://api.tavily.com\"), :timeout in ms (default 60000). Errors if no key is found."
21    (let* ((o (if (null? opts) {} (first opts)))
22           (api-key (or (get o :api-key) (env "TAVILY_API_KEY"))))
23      (when (nil? api-key)
24        (error "tavily: no API key — pass {:api-key \"...\"} or set the TAVILY_API_KEY environment variable"))
25      {:api-key api-key
26       :base-url (string/chop-end (get o :base-url "https://api.tavily.com") "/")
27       :timeout (get o :timeout 60000)}))
28
29  ;; -------------------------------------------------------------------------
30  ;; Private: request plumbing
31  ;; -------------------------------------------------------------------------
32
33  (define (client-headers client)
34    {"Authorization" (string-append "Bearer " (:api-key client))
35     "Content-Type" "application/json"})
36
37  (define (decode-body body)
38    (if (or (nil? body) (string/empty? (string/trim body)))
39      {}
40      (json/decode body)))
41
42  ;; Best error message we can extract from a failed response body. Tavily
43  ;; returns errors as {:detail {:error "..."}} or {:detail "..."}.
44  (define (api-error-message body)
45    (let ((decoded (try (json/decode body) (catch e nil))))
46      (cond
47        ((not (map? decoded)) (string/take (string/trim body) 200))
48        ((and (map? (get decoded :detail))
49              (contains? (get decoded :detail) :error))
50         (get (get decoded :detail) :error))
51        ((string? (get decoded :detail)) (get decoded :detail))
52        ((contains? decoded :error) (get decoded :error))
53        (#t (string/take (string/trim body) 200)))))
54
55  ;; -------------------------------------------------------------------------
56  ;; Escape hatch
57  ;; -------------------------------------------------------------------------
58
59  (define (tavily/request client method path body)
60    "Make a raw Tavily API request. method is \"GET\"/\"POST\"/..., path an API path (\"/search\"), body a map (JSON-encoded) or nil. Returns the decoded JSON body ({} when empty); raises on non-2xx with method, path, status, and the API's error message."
61    (let* ((url (string-append (:base-url client) (string/ensure-start path "/")))
62           (opts {:headers (client-headers client) :timeout (:timeout client)})
63           (resp (if (nil? body)
64                   (http/request method url opts)
65                   (http/request method url opts body)))
66           (status (:status resp)))
67      (if (and (>= status 200) (< status 300))
68        (decode-body (:body resp))
69        (error (format "tavily: ~a ~a → ~a: ~a"
70                       method path status (api-error-message (:body resp)))))))
71
72  ;; -------------------------------------------------------------------------
73  ;; Search
74  ;; -------------------------------------------------------------------------
75
76  (define (tavily/search client query . opts)
77    "Run a web search for a query string. Returns a map with :answer (when requested), :results (a list of {:title :url :content :score}), and :query. opts is an optional map merged into the request body: :search_depth (default \"basic\"), :max_results (default 5), :topic (\"general\"), :include_answer (#f), :include_raw_content (#f), :include_domains, :exclude_domains, :time_range."
78    (when (or (nil? query) (not (string? query)) (string/empty? (string/trim query)))
79      (error "tavily: search query must be a non-empty string — pass a query such as \"latest AI news\""))
80    (let ((o (if (null? opts) {} (first opts))))
81      (tavily/request client "POST" "/search" (assoc o :query query))))
82
83  ;; -------------------------------------------------------------------------
84  ;; Extract
85  ;; -------------------------------------------------------------------------
86
87  (define (tavily/extract client urls . opts)
88    "Extract cleaned content from one or more page URLs. urls is a URL string or a list of URL strings. Returns a map with :results (a list of {:url :raw_content}) and :failed_results. opts is an optional map merged into the request body: :extract_depth (default \"basic\"), :format (\"markdown\"), :include_images (#f)."
89    (when (or (nil? urls)
90              (and (string? urls) (string/empty? (string/trim urls)))
91              (and (list? urls) (empty? urls)))
92      (error "tavily: extract urls must be a URL string or a non-empty list of URL strings — pass e.g. \"https://example.com\""))
93    (let ((o (if (null? opts) {} (first opts))))
94      (tavily/request client "POST" "/extract" (assoc o :urls urls)))))