@upstash/context7-tools-ai-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Upstash, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # Upstash Context7 AI SDK
2
+
3
+ `@upstash/context7-tools-ai-sdk` provides [Vercel AI SDK](https://ai-sdk.dev/) compatible tools and agents that give your AI applications access to up to date library documentation through Context7.
4
+
5
+ Use this package to:
6
+
7
+ - Add documentation lookup tools to your AI SDK workflows with `generateText` or `streamText`
8
+ - Create documentation aware agents using the pre-configured `Context7Agent`
9
+ - Build RAG pipelines that retrieve accurate, version specific code examples
10
+
11
+ The package provides two main tools:
12
+
13
+ - `resolveLibrary` - Searches Context7's database to find the correct library ID
14
+ - `getLibraryDocs` - Fetches documentation for a specific library with optional topic filtering
15
+
16
+ ## Quick Start
17
+
18
+ ### Install
19
+
20
+ ```bash
21
+ npm install @upstash/context7-tools-ai-sdk @upstash/context7-sdk ai zod
22
+ ```
23
+
24
+ ### Get API Key
25
+
26
+ Get your API key from [Context7](https://context7.com)
27
+
28
+ ## Usage
29
+
30
+ ### Using Tools with `generateText`
31
+
32
+ ```typescript
33
+ import { resolveLibrary, getLibraryDocs } from "@upstash/context7-tools-ai-sdk";
34
+ import { generateText, stepCountIs } from "ai";
35
+ import { openai } from "@ai-sdk/openai";
36
+
37
+ const { text } = await generateText({
38
+ model: openai("gpt-4o"),
39
+ prompt: "How do I use React Server Components?",
40
+ tools: {
41
+ resolveLibrary: resolveLibrary(),
42
+ getLibraryDocs: getLibraryDocs(),
43
+ },
44
+ stopWhen: stepCountIs(5),
45
+ });
46
+
47
+ console.log(text);
48
+ ```
49
+
50
+ ### Using the Context7 Agent
51
+
52
+ The package provides a pre-configured agent that handles the multi-step workflow automatically:
53
+
54
+ ```typescript
55
+ import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
56
+ import { anthropic } from "@ai-sdk/anthropic";
57
+
58
+ const agent = new Context7Agent({
59
+ model: anthropic("claude-sonnet-4-20250514"),
60
+ });
61
+
62
+ const { text } = await agent.generate({
63
+ prompt: "How do I set up routing in Next.js?",
64
+ });
65
+
66
+ console.log(text);
67
+ ```
68
+
69
+ ## Configuration
70
+
71
+ ### Environment Variables
72
+
73
+ Set your API key via environment variable:
74
+
75
+ ```sh
76
+ CONTEXT7_API_KEY=ctx7sk-...
77
+ ```
78
+
79
+ Then use tools and agents without explicit configuration:
80
+
81
+ ```typescript
82
+ const tool = resolveLibrary(); // Uses CONTEXT7_API_KEY automatically
83
+ ```
84
+
85
+ ## Docs
86
+
87
+ See the [documentation](https://context7.com/docs/agentic-tools/ai-sdk/getting-started) for details.
88
+
89
+ ## Contributing
90
+
91
+ ### Running tests
92
+
93
+ ```sh
94
+ pnpm test
95
+ ```
96
+
97
+ ### Building
98
+
99
+ ```sh
100
+ pnpm build
101
+ ```
package/dist/agent.cjs ADDED
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/agents/index.ts
21
+ var agents_exports = {};
22
+ __export(agents_exports, {
23
+ Context7Agent: () => Context7Agent
24
+ });
25
+ module.exports = __toCommonJS(agents_exports);
26
+
27
+ // src/agents/context7.ts
28
+ var import_ai3 = require("ai");
29
+
30
+ // src/tools/resolve-library.ts
31
+ var import_ai = require("ai");
32
+ var import_zod = require("zod");
33
+ var import_context7_sdk = require("@upstash/context7-sdk");
34
+
35
+ // src/prompts/system.ts
36
+ var AGENT_PROMPT = `You are a documentation search assistant powered by Context7.
37
+
38
+ CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
39
+
40
+ Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
41
+ - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
42
+ - Call resolveLibrary with just the library name
43
+ - Review ALL the search results returned
44
+
45
+ Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
46
+ - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
47
+ - Name similarity to what the user is looking for
48
+ - Description relevance
49
+ - Source reputation (High/Medium is better)
50
+ - Code snippet coverage (higher is better)
51
+ - Benchmark score (higher is better)
52
+
53
+ Step 3: Call 'getLibraryDocs' with the selected library ID
54
+ - Use the exact library ID from the resolveLibrary results
55
+ - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
56
+ - Start with page=1 (default)
57
+
58
+ Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
59
+ - Use the same library ID and the SAME topic from step 3
60
+ - This gives you more comprehensive documentation
61
+
62
+ Step 5: Provide a clear answer with code examples from the documentation
63
+
64
+ IMPORTANT:
65
+ - You MUST call resolveLibrary first before calling getLibraryDocs
66
+ - Do NOT skip resolveLibrary - it helps you find the correct official documentation
67
+ - Always cite which library ID you used`;
68
+ var RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
69
+
70
+ You MUST call this function before 'getLibraryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
71
+
72
+ Selection Process:
73
+ 1. Analyze the query to understand what library/package the user is looking for
74
+ 2. Return the most relevant match based on:
75
+ - Name similarity to the query (exact matches prioritized)
76
+ - Description relevance to the query's intent
77
+ - Documentation coverage (prioritize libraries with higher Code Snippet counts)
78
+ - Source reputation (consider libraries with High or Medium reputation more authoritative)
79
+ - Benchmark Score: Quality indicator (100 is the highest score)
80
+
81
+ Response Format:
82
+ - Return the selected library ID in a clearly marked section
83
+ - Provide a brief explanation for why this library was chosen
84
+ - If multiple good matches exist, acknowledge this but proceed with the most relevant one
85
+ - If no good matches exist, clearly state this and suggest query refinements
86
+
87
+ For ambiguous queries, request clarification before proceeding with a best-guess match.`;
88
+ var GET_LIBRARY_DOCS_DESCRIPTION = "Fetches up-to-date documentation for a library. You must call 'resolveLibrary' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query. Use mode='code' (default) for API references and code examples, or mode='info' for conceptual guides, narrative information, and architectural questions.";
89
+
90
+ // src/tools/resolve-library.ts
91
+ function resolveLibrary(config = {}) {
92
+ const { apiKey } = config;
93
+ const getClient = () => new import_context7_sdk.Context7({ apiKey });
94
+ return (0, import_ai.tool)({
95
+ description: RESOLVE_LIBRARY_DESCRIPTION,
96
+ inputSchema: import_zod.z.object({
97
+ libraryName: import_zod.z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
98
+ }),
99
+ execute: async ({ libraryName }) => {
100
+ try {
101
+ const client = getClient();
102
+ const response = await client.searchLibrary(libraryName);
103
+ if (!response.results || response.results.length === 0) {
104
+ return {
105
+ success: false,
106
+ error: "No libraries found matching your query.",
107
+ suggestions: "Try a different search term or check the library name."
108
+ };
109
+ }
110
+ return {
111
+ success: true,
112
+ results: response.results,
113
+ totalResults: response.results.length
114
+ };
115
+ } catch (error) {
116
+ return {
117
+ success: false,
118
+ error: error instanceof Error ? error.message : "Failed to search libraries",
119
+ suggestions: "Check your API key and try again, or try a different search term."
120
+ };
121
+ }
122
+ }
123
+ });
124
+ }
125
+
126
+ // src/tools/get-library-docs.ts
127
+ var import_ai2 = require("ai");
128
+ var import_zod2 = require("zod");
129
+ var import_context7_sdk2 = require("@upstash/context7-sdk");
130
+ function getLibraryDocs(config = {}) {
131
+ const { apiKey, defaultMaxResults = 10 } = config;
132
+ const getClient = () => new import_context7_sdk2.Context7({ apiKey });
133
+ return (0, import_ai2.tool)({
134
+ description: GET_LIBRARY_DOCS_DESCRIPTION,
135
+ inputSchema: import_zod2.z.object({
136
+ libraryId: import_zod2.z.string().describe(
137
+ "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolveLibrary' or directly from user query in the format '/org/project' or '/org/project/version'."
138
+ ),
139
+ mode: import_zod2.z.enum(["code", "info"]).optional().default("code").describe(
140
+ "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
141
+ ),
142
+ topic: import_zod2.z.string().optional().describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
143
+ page: import_zod2.z.number().int().min(1).max(10).optional().describe(
144
+ "Page number for pagination (start: 1, default: 1). If the context is not sufficient, try page=2, page=3, page=4, etc. with the same topic."
145
+ )
146
+ }),
147
+ execute: async ({
148
+ libraryId,
149
+ mode = "code",
150
+ topic,
151
+ page = 1
152
+ }) => {
153
+ try {
154
+ const client = getClient();
155
+ const baseOptions = {
156
+ page,
157
+ limit: defaultMaxResults,
158
+ topic: topic?.trim() || void 0
159
+ };
160
+ const response = mode === "info" ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" }) : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
161
+ if (!response.snippets?.length) {
162
+ return {
163
+ success: false,
164
+ error: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolveLibrary' with the package name you wish to retrieve documentation for.",
165
+ libraryId
166
+ };
167
+ }
168
+ return {
169
+ success: true,
170
+ libraryId,
171
+ snippets: response.snippets,
172
+ pagination: response.pagination,
173
+ totalTokens: response.totalTokens
174
+ };
175
+ } catch (error) {
176
+ return {
177
+ success: false,
178
+ error: error instanceof Error ? error.message : "Failed to fetch documentation",
179
+ libraryId
180
+ };
181
+ }
182
+ }
183
+ });
184
+ }
185
+
186
+ // src/agents/context7.ts
187
+ var Context7Agent = class extends import_ai3.Experimental_Agent {
188
+ constructor(config) {
189
+ const {
190
+ model,
191
+ stopWhen = (0, import_ai3.stepCountIs)(5),
192
+ system,
193
+ apiKey,
194
+ defaultMaxResults,
195
+ tools,
196
+ ...agentSettings
197
+ } = config;
198
+ const context7Config = { apiKey, defaultMaxResults };
199
+ super({
200
+ ...agentSettings,
201
+ model,
202
+ system: system || AGENT_PROMPT,
203
+ tools: {
204
+ ...tools,
205
+ resolveLibrary: resolveLibrary(context7Config),
206
+ getLibraryDocs: getLibraryDocs(context7Config)
207
+ },
208
+ stopWhen
209
+ });
210
+ }
211
+ };
212
+ // Annotate the CommonJS export names for ESM import in node:
213
+ 0 && (module.exports = {
214
+ Context7Agent
215
+ });
@@ -0,0 +1,44 @@
1
+ import { Experimental_Agent, ToolSet, Experimental_AgentSettings } from 'ai';
2
+
3
+ /**
4
+ * Configuration for Context7 agent.
5
+ */
6
+ interface Context7AgentConfig extends Experimental_AgentSettings<ToolSet> {
7
+ /**
8
+ * Context7 API key. If not provided, uses the CONTEXT7_API_KEY environment variable.
9
+ */
10
+ apiKey?: string;
11
+ /**
12
+ * Default maximum number of documentation results per request.
13
+ * @default 10
14
+ */
15
+ defaultMaxResults?: number;
16
+ }
17
+ /**
18
+ * Context7 documentation search agent
19
+ *
20
+ * The agent follows a multi-step workflow:
21
+ * 1. Resolves library names to Context7 library IDs
22
+ * 2. Fetches documentation for the resolved library
23
+ * 3. Provides answers with code examples
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * import { Context7Agent } from '@upstash/context7-tools-ai-sdk';
28
+ * import { anthropic } from '@ai-sdk/anthropic';
29
+ *
30
+ * const agent = new Context7Agent({
31
+ * model: anthropic('claude-sonnet-4-20250514'),
32
+ * apiKey: 'your-context7-api-key',
33
+ * });
34
+ *
35
+ * const result = await agent.generate({
36
+ * prompt: 'How do I use React Server Components?',
37
+ * });
38
+ * ```
39
+ */
40
+ declare class Context7Agent extends Experimental_Agent<ToolSet> {
41
+ constructor(config: Context7AgentConfig);
42
+ }
43
+
44
+ export { Context7Agent, type Context7AgentConfig };
@@ -0,0 +1,44 @@
1
+ import { Experimental_Agent, ToolSet, Experimental_AgentSettings } from 'ai';
2
+
3
+ /**
4
+ * Configuration for Context7 agent.
5
+ */
6
+ interface Context7AgentConfig extends Experimental_AgentSettings<ToolSet> {
7
+ /**
8
+ * Context7 API key. If not provided, uses the CONTEXT7_API_KEY environment variable.
9
+ */
10
+ apiKey?: string;
11
+ /**
12
+ * Default maximum number of documentation results per request.
13
+ * @default 10
14
+ */
15
+ defaultMaxResults?: number;
16
+ }
17
+ /**
18
+ * Context7 documentation search agent
19
+ *
20
+ * The agent follows a multi-step workflow:
21
+ * 1. Resolves library names to Context7 library IDs
22
+ * 2. Fetches documentation for the resolved library
23
+ * 3. Provides answers with code examples
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * import { Context7Agent } from '@upstash/context7-tools-ai-sdk';
28
+ * import { anthropic } from '@ai-sdk/anthropic';
29
+ *
30
+ * const agent = new Context7Agent({
31
+ * model: anthropic('claude-sonnet-4-20250514'),
32
+ * apiKey: 'your-context7-api-key',
33
+ * });
34
+ *
35
+ * const result = await agent.generate({
36
+ * prompt: 'How do I use React Server Components?',
37
+ * });
38
+ * ```
39
+ */
40
+ declare class Context7Agent extends Experimental_Agent<ToolSet> {
41
+ constructor(config: Context7AgentConfig);
42
+ }
43
+
44
+ export { Context7Agent, type Context7AgentConfig };
package/dist/agent.js ADDED
@@ -0,0 +1,6 @@
1
+ import {
2
+ Context7Agent
3
+ } from "./chunk-AMSBQOUU.js";
4
+ export {
5
+ Context7Agent
6
+ };
@@ -0,0 +1,206 @@
1
+ // src/agents/context7.ts
2
+ import {
3
+ Experimental_Agent as Agent,
4
+ stepCountIs
5
+ } from "ai";
6
+
7
+ // src/tools/resolve-library.ts
8
+ import { tool } from "ai";
9
+ import { z } from "zod";
10
+ import { Context7 } from "@upstash/context7-sdk";
11
+
12
+ // src/prompts/system.ts
13
+ var SYSTEM_PROMPT = `You are a documentation search assistant powered by Context7.
14
+
15
+ Your role is to help users find accurate, up-to-date documentation for libraries and frameworks.
16
+
17
+ When answering questions:
18
+ 1. Search for the relevant library documentation
19
+ 2. Provide code examples when available
20
+ 3. Cite your sources by mentioning the library ID used`;
21
+ var AGENT_PROMPT = `You are a documentation search assistant powered by Context7.
22
+
23
+ CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
24
+
25
+ Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
26
+ - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
27
+ - Call resolveLibrary with just the library name
28
+ - Review ALL the search results returned
29
+
30
+ Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
31
+ - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
32
+ - Name similarity to what the user is looking for
33
+ - Description relevance
34
+ - Source reputation (High/Medium is better)
35
+ - Code snippet coverage (higher is better)
36
+ - Benchmark score (higher is better)
37
+
38
+ Step 3: Call 'getLibraryDocs' with the selected library ID
39
+ - Use the exact library ID from the resolveLibrary results
40
+ - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
41
+ - Start with page=1 (default)
42
+
43
+ Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
44
+ - Use the same library ID and the SAME topic from step 3
45
+ - This gives you more comprehensive documentation
46
+
47
+ Step 5: Provide a clear answer with code examples from the documentation
48
+
49
+ IMPORTANT:
50
+ - You MUST call resolveLibrary first before calling getLibraryDocs
51
+ - Do NOT skip resolveLibrary - it helps you find the correct official documentation
52
+ - Always cite which library ID you used`;
53
+ var RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
54
+
55
+ You MUST call this function before 'getLibraryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
56
+
57
+ Selection Process:
58
+ 1. Analyze the query to understand what library/package the user is looking for
59
+ 2. Return the most relevant match based on:
60
+ - Name similarity to the query (exact matches prioritized)
61
+ - Description relevance to the query's intent
62
+ - Documentation coverage (prioritize libraries with higher Code Snippet counts)
63
+ - Source reputation (consider libraries with High or Medium reputation more authoritative)
64
+ - Benchmark Score: Quality indicator (100 is the highest score)
65
+
66
+ Response Format:
67
+ - Return the selected library ID in a clearly marked section
68
+ - Provide a brief explanation for why this library was chosen
69
+ - If multiple good matches exist, acknowledge this but proceed with the most relevant one
70
+ - If no good matches exist, clearly state this and suggest query refinements
71
+
72
+ For ambiguous queries, request clarification before proceeding with a best-guess match.`;
73
+ var GET_LIBRARY_DOCS_DESCRIPTION = "Fetches up-to-date documentation for a library. You must call 'resolveLibrary' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query. Use mode='code' (default) for API references and code examples, or mode='info' for conceptual guides, narrative information, and architectural questions.";
74
+
75
+ // src/tools/resolve-library.ts
76
+ function resolveLibrary(config = {}) {
77
+ const { apiKey } = config;
78
+ const getClient = () => new Context7({ apiKey });
79
+ return tool({
80
+ description: RESOLVE_LIBRARY_DESCRIPTION,
81
+ inputSchema: z.object({
82
+ libraryName: z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
83
+ }),
84
+ execute: async ({ libraryName }) => {
85
+ try {
86
+ const client = getClient();
87
+ const response = await client.searchLibrary(libraryName);
88
+ if (!response.results || response.results.length === 0) {
89
+ return {
90
+ success: false,
91
+ error: "No libraries found matching your query.",
92
+ suggestions: "Try a different search term or check the library name."
93
+ };
94
+ }
95
+ return {
96
+ success: true,
97
+ results: response.results,
98
+ totalResults: response.results.length
99
+ };
100
+ } catch (error) {
101
+ return {
102
+ success: false,
103
+ error: error instanceof Error ? error.message : "Failed to search libraries",
104
+ suggestions: "Check your API key and try again, or try a different search term."
105
+ };
106
+ }
107
+ }
108
+ });
109
+ }
110
+
111
+ // src/tools/get-library-docs.ts
112
+ import { tool as tool2 } from "ai";
113
+ import { z as z2 } from "zod";
114
+ import { Context7 as Context72 } from "@upstash/context7-sdk";
115
+ function getLibraryDocs(config = {}) {
116
+ const { apiKey, defaultMaxResults = 10 } = config;
117
+ const getClient = () => new Context72({ apiKey });
118
+ return tool2({
119
+ description: GET_LIBRARY_DOCS_DESCRIPTION,
120
+ inputSchema: z2.object({
121
+ libraryId: z2.string().describe(
122
+ "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolveLibrary' or directly from user query in the format '/org/project' or '/org/project/version'."
123
+ ),
124
+ mode: z2.enum(["code", "info"]).optional().default("code").describe(
125
+ "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
126
+ ),
127
+ topic: z2.string().optional().describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
128
+ page: z2.number().int().min(1).max(10).optional().describe(
129
+ "Page number for pagination (start: 1, default: 1). If the context is not sufficient, try page=2, page=3, page=4, etc. with the same topic."
130
+ )
131
+ }),
132
+ execute: async ({
133
+ libraryId,
134
+ mode = "code",
135
+ topic,
136
+ page = 1
137
+ }) => {
138
+ try {
139
+ const client = getClient();
140
+ const baseOptions = {
141
+ page,
142
+ limit: defaultMaxResults,
143
+ topic: topic?.trim() || void 0
144
+ };
145
+ const response = mode === "info" ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" }) : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
146
+ if (!response.snippets?.length) {
147
+ return {
148
+ success: false,
149
+ error: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolveLibrary' with the package name you wish to retrieve documentation for.",
150
+ libraryId
151
+ };
152
+ }
153
+ return {
154
+ success: true,
155
+ libraryId,
156
+ snippets: response.snippets,
157
+ pagination: response.pagination,
158
+ totalTokens: response.totalTokens
159
+ };
160
+ } catch (error) {
161
+ return {
162
+ success: false,
163
+ error: error instanceof Error ? error.message : "Failed to fetch documentation",
164
+ libraryId
165
+ };
166
+ }
167
+ }
168
+ });
169
+ }
170
+
171
+ // src/agents/context7.ts
172
+ var Context7Agent = class extends Agent {
173
+ constructor(config) {
174
+ const {
175
+ model,
176
+ stopWhen = stepCountIs(5),
177
+ system,
178
+ apiKey,
179
+ defaultMaxResults,
180
+ tools,
181
+ ...agentSettings
182
+ } = config;
183
+ const context7Config = { apiKey, defaultMaxResults };
184
+ super({
185
+ ...agentSettings,
186
+ model,
187
+ system: system || AGENT_PROMPT,
188
+ tools: {
189
+ ...tools,
190
+ resolveLibrary: resolveLibrary(context7Config),
191
+ getLibraryDocs: getLibraryDocs(context7Config)
192
+ },
193
+ stopWhen
194
+ });
195
+ }
196
+ };
197
+
198
+ export {
199
+ SYSTEM_PROMPT,
200
+ AGENT_PROMPT,
201
+ RESOLVE_LIBRARY_DESCRIPTION,
202
+ GET_LIBRARY_DOCS_DESCRIPTION,
203
+ resolveLibrary,
204
+ getLibraryDocs,
205
+ Context7Agent
206
+ };
package/dist/index.cjs ADDED
@@ -0,0 +1,235 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AGENT_PROMPT: () => AGENT_PROMPT,
24
+ Context7Agent: () => Context7Agent,
25
+ GET_LIBRARY_DOCS_DESCRIPTION: () => GET_LIBRARY_DOCS_DESCRIPTION,
26
+ RESOLVE_LIBRARY_DESCRIPTION: () => RESOLVE_LIBRARY_DESCRIPTION,
27
+ SYSTEM_PROMPT: () => SYSTEM_PROMPT,
28
+ getLibraryDocs: () => getLibraryDocs,
29
+ resolveLibrary: () => resolveLibrary
30
+ });
31
+ module.exports = __toCommonJS(src_exports);
32
+
33
+ // src/agents/context7.ts
34
+ var import_ai3 = require("ai");
35
+
36
+ // src/tools/resolve-library.ts
37
+ var import_ai = require("ai");
38
+ var import_zod = require("zod");
39
+ var import_context7_sdk = require("@upstash/context7-sdk");
40
+
41
+ // src/prompts/system.ts
42
+ var SYSTEM_PROMPT = `You are a documentation search assistant powered by Context7.
43
+
44
+ Your role is to help users find accurate, up-to-date documentation for libraries and frameworks.
45
+
46
+ When answering questions:
47
+ 1. Search for the relevant library documentation
48
+ 2. Provide code examples when available
49
+ 3. Cite your sources by mentioning the library ID used`;
50
+ var AGENT_PROMPT = `You are a documentation search assistant powered by Context7.
51
+
52
+ CRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:
53
+
54
+ Step 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query
55
+ - Extract the main library/framework name (e.g., "React", "Next.js", "Vue")
56
+ - Call resolveLibrary with just the library name
57
+ - Review ALL the search results returned
58
+
59
+ Step 2: Analyze the results from resolveLibrary and select the BEST library ID based on:
60
+ - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)
61
+ - Name similarity to what the user is looking for
62
+ - Description relevance
63
+ - Source reputation (High/Medium is better)
64
+ - Code snippet coverage (higher is better)
65
+ - Benchmark score (higher is better)
66
+
67
+ Step 3: Call 'getLibraryDocs' with the selected library ID
68
+ - Use the exact library ID from the resolveLibrary results
69
+ - ALWAYS extract and include a relevant topic from the user's query (e.g., "Server-Side Rendering", "routing", "authentication")
70
+ - Start with page=1 (default)
71
+
72
+ Step 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2
73
+ - Use the same library ID and the SAME topic from step 3
74
+ - This gives you more comprehensive documentation
75
+
76
+ Step 5: Provide a clear answer with code examples from the documentation
77
+
78
+ IMPORTANT:
79
+ - You MUST call resolveLibrary first before calling getLibraryDocs
80
+ - Do NOT skip resolveLibrary - it helps you find the correct official documentation
81
+ - Always cite which library ID you used`;
82
+ var RESOLVE_LIBRARY_DESCRIPTION = `Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.
83
+
84
+ You MUST call this function before 'getLibraryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.
85
+
86
+ Selection Process:
87
+ 1. Analyze the query to understand what library/package the user is looking for
88
+ 2. Return the most relevant match based on:
89
+ - Name similarity to the query (exact matches prioritized)
90
+ - Description relevance to the query's intent
91
+ - Documentation coverage (prioritize libraries with higher Code Snippet counts)
92
+ - Source reputation (consider libraries with High or Medium reputation more authoritative)
93
+ - Benchmark Score: Quality indicator (100 is the highest score)
94
+
95
+ Response Format:
96
+ - Return the selected library ID in a clearly marked section
97
+ - Provide a brief explanation for why this library was chosen
98
+ - If multiple good matches exist, acknowledge this but proceed with the most relevant one
99
+ - If no good matches exist, clearly state this and suggest query refinements
100
+
101
+ For ambiguous queries, request clarification before proceeding with a best-guess match.`;
102
+ var GET_LIBRARY_DOCS_DESCRIPTION = "Fetches up-to-date documentation for a library. You must call 'resolveLibrary' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query. Use mode='code' (default) for API references and code examples, or mode='info' for conceptual guides, narrative information, and architectural questions.";
103
+
104
+ // src/tools/resolve-library.ts
105
+ function resolveLibrary(config = {}) {
106
+ const { apiKey } = config;
107
+ const getClient = () => new import_context7_sdk.Context7({ apiKey });
108
+ return (0, import_ai.tool)({
109
+ description: RESOLVE_LIBRARY_DESCRIPTION,
110
+ inputSchema: import_zod.z.object({
111
+ libraryName: import_zod.z.string().describe("Library name to search for and retrieve a Context7-compatible library ID.")
112
+ }),
113
+ execute: async ({ libraryName }) => {
114
+ try {
115
+ const client = getClient();
116
+ const response = await client.searchLibrary(libraryName);
117
+ if (!response.results || response.results.length === 0) {
118
+ return {
119
+ success: false,
120
+ error: "No libraries found matching your query.",
121
+ suggestions: "Try a different search term or check the library name."
122
+ };
123
+ }
124
+ return {
125
+ success: true,
126
+ results: response.results,
127
+ totalResults: response.results.length
128
+ };
129
+ } catch (error) {
130
+ return {
131
+ success: false,
132
+ error: error instanceof Error ? error.message : "Failed to search libraries",
133
+ suggestions: "Check your API key and try again, or try a different search term."
134
+ };
135
+ }
136
+ }
137
+ });
138
+ }
139
+
140
+ // src/tools/get-library-docs.ts
141
+ var import_ai2 = require("ai");
142
+ var import_zod2 = require("zod");
143
+ var import_context7_sdk2 = require("@upstash/context7-sdk");
144
+ function getLibraryDocs(config = {}) {
145
+ const { apiKey, defaultMaxResults = 10 } = config;
146
+ const getClient = () => new import_context7_sdk2.Context7({ apiKey });
147
+ return (0, import_ai2.tool)({
148
+ description: GET_LIBRARY_DOCS_DESCRIPTION,
149
+ inputSchema: import_zod2.z.object({
150
+ libraryId: import_zod2.z.string().describe(
151
+ "Exact Context7-compatible library ID (e.g., '/mongodb/docs', '/vercel/next.js', '/supabase/supabase', '/vercel/next.js/v14.3.0-canary.87') retrieved from 'resolveLibrary' or directly from user query in the format '/org/project' or '/org/project/version'."
152
+ ),
153
+ mode: import_zod2.z.enum(["code", "info"]).optional().default("code").describe(
154
+ "Documentation mode: 'code' for API references and code examples (default), 'info' for conceptual guides, narrative information, and architectural questions."
155
+ ),
156
+ topic: import_zod2.z.string().optional().describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),
157
+ page: import_zod2.z.number().int().min(1).max(10).optional().describe(
158
+ "Page number for pagination (start: 1, default: 1). If the context is not sufficient, try page=2, page=3, page=4, etc. with the same topic."
159
+ )
160
+ }),
161
+ execute: async ({
162
+ libraryId,
163
+ mode = "code",
164
+ topic,
165
+ page = 1
166
+ }) => {
167
+ try {
168
+ const client = getClient();
169
+ const baseOptions = {
170
+ page,
171
+ limit: defaultMaxResults,
172
+ topic: topic?.trim() || void 0
173
+ };
174
+ const response = mode === "info" ? await client.getDocs(libraryId, { ...baseOptions, mode: "info" }) : await client.getDocs(libraryId, { ...baseOptions, mode: "code" });
175
+ if (!response.snippets?.length) {
176
+ return {
177
+ success: false,
178
+ error: "Documentation not found or not finalized for this library. This might have happened because you used an invalid Context7-compatible library ID. To get a valid Context7-compatible library ID, use the 'resolveLibrary' with the package name you wish to retrieve documentation for.",
179
+ libraryId
180
+ };
181
+ }
182
+ return {
183
+ success: true,
184
+ libraryId,
185
+ snippets: response.snippets,
186
+ pagination: response.pagination,
187
+ totalTokens: response.totalTokens
188
+ };
189
+ } catch (error) {
190
+ return {
191
+ success: false,
192
+ error: error instanceof Error ? error.message : "Failed to fetch documentation",
193
+ libraryId
194
+ };
195
+ }
196
+ }
197
+ });
198
+ }
199
+
200
+ // src/agents/context7.ts
201
+ var Context7Agent = class extends import_ai3.Experimental_Agent {
202
+ constructor(config) {
203
+ const {
204
+ model,
205
+ stopWhen = (0, import_ai3.stepCountIs)(5),
206
+ system,
207
+ apiKey,
208
+ defaultMaxResults,
209
+ tools,
210
+ ...agentSettings
211
+ } = config;
212
+ const context7Config = { apiKey, defaultMaxResults };
213
+ super({
214
+ ...agentSettings,
215
+ model,
216
+ system: system || AGENT_PROMPT,
217
+ tools: {
218
+ ...tools,
219
+ resolveLibrary: resolveLibrary(context7Config),
220
+ getLibraryDocs: getLibraryDocs(context7Config)
221
+ },
222
+ stopWhen
223
+ });
224
+ }
225
+ };
226
+ // Annotate the CommonJS export names for ESM import in node:
227
+ 0 && (module.exports = {
228
+ AGENT_PROMPT,
229
+ Context7Agent,
230
+ GET_LIBRARY_DOCS_DESCRIPTION,
231
+ RESOLVE_LIBRARY_DESCRIPTION,
232
+ SYSTEM_PROMPT,
233
+ getLibraryDocs,
234
+ resolveLibrary
235
+ });
@@ -0,0 +1,130 @@
1
+ export { Context7Agent, Context7AgentConfig } from './agent.cjs';
2
+ import * as ai from 'ai';
3
+ import * as _upstash_context7_sdk from '@upstash/context7-sdk';
4
+ export { CodeDocsResponse, InfoDocsResponse, Pagination, SearchLibraryResponse, SearchResult, TextDocsResponse } from '@upstash/context7-sdk';
5
+
6
+ /**
7
+ * Configuration for Context7 tools
8
+ */
9
+ interface Context7ToolsConfig {
10
+ /**
11
+ * Context7 API key. If not provided, will use CONTEXT7_API_KEY environment variable.
12
+ */
13
+ apiKey?: string;
14
+ /**
15
+ * Default maximum number of documentation results per page.
16
+ * @default 10
17
+ */
18
+ defaultMaxResults?: number;
19
+ }
20
+
21
+ /**
22
+ * Tool to resolve a library name to a Context7-compatible library ID.
23
+ *
24
+ * Can be called with or without configuration. Uses CONTEXT7_API_KEY environment
25
+ * variable for authentication when no API key is provided.
26
+ *
27
+ * @param config Optional configuration options
28
+ * @returns AI SDK tool for library resolution
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
33
+ * import { generateText, stepCountIs } from 'ai';
34
+ * import { openai } from '@ai-sdk/openai';
35
+ *
36
+ * const { text } = await generateText({
37
+ * model: openai('gpt-4o'),
38
+ * prompt: 'Find React documentation about hooks',
39
+ * tools: {
40
+ * resolveLibrary: resolveLibrary(),
41
+ * getLibraryDocs: getLibraryDocs(),
42
+ * },
43
+ * stopWhen: stepCountIs(5),
44
+ * });
45
+ * ```
46
+ */
47
+ declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
48
+ libraryName: string;
49
+ }, {
50
+ success: boolean;
51
+ error: string;
52
+ suggestions: string;
53
+ results?: undefined;
54
+ totalResults?: undefined;
55
+ } | {
56
+ success: boolean;
57
+ results: _upstash_context7_sdk.SearchResult[];
58
+ totalResults: number;
59
+ error?: undefined;
60
+ suggestions?: undefined;
61
+ }>;
62
+
63
+ /**
64
+ * Tool to fetch documentation for a library using its Context7 library ID.
65
+ *
66
+ * Can be called with or without configuration. Uses CONTEXT7_API_KEY environment
67
+ * variable for authentication when no API key is provided.
68
+ *
69
+ * @param config Optional configuration options
70
+ * @returns AI SDK tool for fetching library documentation
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
75
+ * import { generateText, stepCountIs } from 'ai';
76
+ * import { openai } from '@ai-sdk/openai';
77
+ *
78
+ * const { text } = await generateText({
79
+ * model: openai('gpt-4o'),
80
+ * prompt: 'Find React documentation about hooks',
81
+ * tools: {
82
+ * resolveLibrary: resolveLibrary(),
83
+ * getLibraryDocs: getLibraryDocs(),
84
+ * },
85
+ * stopWhen: stepCountIs(5),
86
+ * });
87
+ * ```
88
+ */
89
+ declare function getLibraryDocs(config?: Context7ToolsConfig): ai.Tool<{
90
+ libraryId: string;
91
+ mode?: "code" | "info";
92
+ topic?: string;
93
+ page?: number;
94
+ }, {
95
+ success: boolean;
96
+ error: string;
97
+ libraryId: string;
98
+ snippets?: undefined;
99
+ pagination?: undefined;
100
+ totalTokens?: undefined;
101
+ } | {
102
+ success: boolean;
103
+ libraryId: string;
104
+ snippets: _upstash_context7_sdk.CodeSnippet[] | _upstash_context7_sdk.InfoSnippet[];
105
+ pagination: _upstash_context7_sdk.Pagination;
106
+ totalTokens: number;
107
+ error?: undefined;
108
+ }>;
109
+
110
+ /**
111
+ * System prompts for Context7 AI SDK agents
112
+ */
113
+ /**
114
+ * Basic documentation assistant prompt
115
+ */
116
+ declare const SYSTEM_PROMPT = "You are a documentation search assistant powered by Context7.\n\nYour role is to help users find accurate, up-to-date documentation for libraries and frameworks.\n\nWhen answering questions:\n1. Search for the relevant library documentation\n2. Provide code examples when available\n3. Cite your sources by mentioning the library ID used";
117
+ /**
118
+ * Detailed multi-step workflow prompt for comprehensive documentation retrieval
119
+ */
120
+ declare const AGENT_PROMPT = "You are a documentation search assistant powered by Context7.\n\nCRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:\n\nStep 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query\n - Extract the main library/framework name (e.g., \"React\", \"Next.js\", \"Vue\")\n - Call resolveLibrary with just the library name\n - Review ALL the search results returned\n\nStep 2: Analyze the results from resolveLibrary and select the BEST library ID based on:\n - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)\n - Name similarity to what the user is looking for\n - Description relevance\n - Source reputation (High/Medium is better)\n - Code snippet coverage (higher is better)\n - Benchmark score (higher is better)\n\nStep 3: Call 'getLibraryDocs' with the selected library ID\n - Use the exact library ID from the resolveLibrary results\n - ALWAYS extract and include a relevant topic from the user's query (e.g., \"Server-Side Rendering\", \"routing\", \"authentication\")\n - Start with page=1 (default)\n\nStep 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2\n - Use the same library ID and the SAME topic from step 3\n - This gives you more comprehensive documentation\n\nStep 5: Provide a clear answer with code examples from the documentation\n\nIMPORTANT:\n- You MUST call resolveLibrary first before calling getLibraryDocs\n- Do NOT skip resolveLibrary - it helps you find the correct official documentation\n- Always cite which library ID you used";
121
+ /**
122
+ * Library resolution tool description
123
+ */
124
+ declare const RESOLVE_LIBRARY_DESCRIPTION = "Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.\n\nYou MUST call this function before 'getLibraryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.\n\nSelection Process:\n1. Analyze the query to understand what library/package the user is looking for\n2. Return the most relevant match based on:\n- Name similarity to the query (exact matches prioritized)\n- Description relevance to the query's intent\n- Documentation coverage (prioritize libraries with higher Code Snippet counts)\n- Source reputation (consider libraries with High or Medium reputation more authoritative)\n- Benchmark Score: Quality indicator (100 is the highest score)\n\nResponse Format:\n- Return the selected library ID in a clearly marked section\n- Provide a brief explanation for why this library was chosen\n- If multiple good matches exist, acknowledge this but proceed with the most relevant one\n- If no good matches exist, clearly state this and suggest query refinements\n\nFor ambiguous queries, request clarification before proceeding with a best-guess match.";
125
+ /**
126
+ * Get library docs tool description
127
+ */
128
+ declare const GET_LIBRARY_DOCS_DESCRIPTION = "Fetches up-to-date documentation for a library. You must call 'resolveLibrary' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query. Use mode='code' (default) for API references and code examples, or mode='info' for conceptual guides, narrative information, and architectural questions.";
129
+
130
+ export { AGENT_PROMPT, type Context7ToolsConfig, GET_LIBRARY_DOCS_DESCRIPTION, RESOLVE_LIBRARY_DESCRIPTION, SYSTEM_PROMPT, getLibraryDocs, resolveLibrary };
@@ -0,0 +1,130 @@
1
+ export { Context7Agent, Context7AgentConfig } from './agent.js';
2
+ import * as ai from 'ai';
3
+ import * as _upstash_context7_sdk from '@upstash/context7-sdk';
4
+ export { CodeDocsResponse, InfoDocsResponse, Pagination, SearchLibraryResponse, SearchResult, TextDocsResponse } from '@upstash/context7-sdk';
5
+
6
+ /**
7
+ * Configuration for Context7 tools
8
+ */
9
+ interface Context7ToolsConfig {
10
+ /**
11
+ * Context7 API key. If not provided, will use CONTEXT7_API_KEY environment variable.
12
+ */
13
+ apiKey?: string;
14
+ /**
15
+ * Default maximum number of documentation results per page.
16
+ * @default 10
17
+ */
18
+ defaultMaxResults?: number;
19
+ }
20
+
21
+ /**
22
+ * Tool to resolve a library name to a Context7-compatible library ID.
23
+ *
24
+ * Can be called with or without configuration. Uses CONTEXT7_API_KEY environment
25
+ * variable for authentication when no API key is provided.
26
+ *
27
+ * @param config Optional configuration options
28
+ * @returns AI SDK tool for library resolution
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
33
+ * import { generateText, stepCountIs } from 'ai';
34
+ * import { openai } from '@ai-sdk/openai';
35
+ *
36
+ * const { text } = await generateText({
37
+ * model: openai('gpt-4o'),
38
+ * prompt: 'Find React documentation about hooks',
39
+ * tools: {
40
+ * resolveLibrary: resolveLibrary(),
41
+ * getLibraryDocs: getLibraryDocs(),
42
+ * },
43
+ * stopWhen: stepCountIs(5),
44
+ * });
45
+ * ```
46
+ */
47
+ declare function resolveLibrary(config?: Context7ToolsConfig): ai.Tool<{
48
+ libraryName: string;
49
+ }, {
50
+ success: boolean;
51
+ error: string;
52
+ suggestions: string;
53
+ results?: undefined;
54
+ totalResults?: undefined;
55
+ } | {
56
+ success: boolean;
57
+ results: _upstash_context7_sdk.SearchResult[];
58
+ totalResults: number;
59
+ error?: undefined;
60
+ suggestions?: undefined;
61
+ }>;
62
+
63
+ /**
64
+ * Tool to fetch documentation for a library using its Context7 library ID.
65
+ *
66
+ * Can be called with or without configuration. Uses CONTEXT7_API_KEY environment
67
+ * variable for authentication when no API key is provided.
68
+ *
69
+ * @param config Optional configuration options
70
+ * @returns AI SDK tool for fetching library documentation
71
+ *
72
+ * @example
73
+ * ```typescript
74
+ * import { resolveLibrary, getLibraryDocs } from '@upstash/context7-tools-ai-sdk';
75
+ * import { generateText, stepCountIs } from 'ai';
76
+ * import { openai } from '@ai-sdk/openai';
77
+ *
78
+ * const { text } = await generateText({
79
+ * model: openai('gpt-4o'),
80
+ * prompt: 'Find React documentation about hooks',
81
+ * tools: {
82
+ * resolveLibrary: resolveLibrary(),
83
+ * getLibraryDocs: getLibraryDocs(),
84
+ * },
85
+ * stopWhen: stepCountIs(5),
86
+ * });
87
+ * ```
88
+ */
89
+ declare function getLibraryDocs(config?: Context7ToolsConfig): ai.Tool<{
90
+ libraryId: string;
91
+ mode?: "code" | "info";
92
+ topic?: string;
93
+ page?: number;
94
+ }, {
95
+ success: boolean;
96
+ error: string;
97
+ libraryId: string;
98
+ snippets?: undefined;
99
+ pagination?: undefined;
100
+ totalTokens?: undefined;
101
+ } | {
102
+ success: boolean;
103
+ libraryId: string;
104
+ snippets: _upstash_context7_sdk.CodeSnippet[] | _upstash_context7_sdk.InfoSnippet[];
105
+ pagination: _upstash_context7_sdk.Pagination;
106
+ totalTokens: number;
107
+ error?: undefined;
108
+ }>;
109
+
110
+ /**
111
+ * System prompts for Context7 AI SDK agents
112
+ */
113
+ /**
114
+ * Basic documentation assistant prompt
115
+ */
116
+ declare const SYSTEM_PROMPT = "You are a documentation search assistant powered by Context7.\n\nYour role is to help users find accurate, up-to-date documentation for libraries and frameworks.\n\nWhen answering questions:\n1. Search for the relevant library documentation\n2. Provide code examples when available\n3. Cite your sources by mentioning the library ID used";
117
+ /**
118
+ * Detailed multi-step workflow prompt for comprehensive documentation retrieval
119
+ */
120
+ declare const AGENT_PROMPT = "You are a documentation search assistant powered by Context7.\n\nCRITICAL WORKFLOW - YOU MUST FOLLOW THESE STEPS:\n\nStep 1: ALWAYS start by calling 'resolveLibrary' with the library name from the user's query\n - Extract the main library/framework name (e.g., \"React\", \"Next.js\", \"Vue\")\n - Call resolveLibrary with just the library name\n - Review ALL the search results returned\n\nStep 2: Analyze the results from resolveLibrary and select the BEST library ID based on:\n - Official sources (e.g., /reactjs/react.dev for React, /vercel/next.js for Next.js)\n - Name similarity to what the user is looking for\n - Description relevance\n - Source reputation (High/Medium is better)\n - Code snippet coverage (higher is better)\n - Benchmark score (higher is better)\n\nStep 3: Call 'getLibraryDocs' with the selected library ID\n - Use the exact library ID from the resolveLibrary results\n - ALWAYS extract and include a relevant topic from the user's query (e.g., \"Server-Side Rendering\", \"routing\", \"authentication\")\n - Start with page=1 (default)\n\nStep 4: If the documentation from page 1 isn't sufficient, call 'getLibraryDocs' again with page=2\n - Use the same library ID and the SAME topic from step 3\n - This gives you more comprehensive documentation\n\nStep 5: Provide a clear answer with code examples from the documentation\n\nIMPORTANT:\n- You MUST call resolveLibrary first before calling getLibraryDocs\n- Do NOT skip resolveLibrary - it helps you find the correct official documentation\n- Always cite which library ID you used";
121
+ /**
122
+ * Library resolution tool description
123
+ */
124
+ declare const RESOLVE_LIBRARY_DESCRIPTION = "Resolves a package/product name to a Context7-compatible library ID and returns a list of matching libraries.\n\nYou MUST call this function before 'getLibraryDocs' to obtain a valid Context7-compatible library ID UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query.\n\nSelection Process:\n1. Analyze the query to understand what library/package the user is looking for\n2. Return the most relevant match based on:\n- Name similarity to the query (exact matches prioritized)\n- Description relevance to the query's intent\n- Documentation coverage (prioritize libraries with higher Code Snippet counts)\n- Source reputation (consider libraries with High or Medium reputation more authoritative)\n- Benchmark Score: Quality indicator (100 is the highest score)\n\nResponse Format:\n- Return the selected library ID in a clearly marked section\n- Provide a brief explanation for why this library was chosen\n- If multiple good matches exist, acknowledge this but proceed with the most relevant one\n- If no good matches exist, clearly state this and suggest query refinements\n\nFor ambiguous queries, request clarification before proceeding with a best-guess match.";
125
+ /**
126
+ * Get library docs tool description
127
+ */
128
+ declare const GET_LIBRARY_DOCS_DESCRIPTION = "Fetches up-to-date documentation for a library. You must call 'resolveLibrary' first to obtain the exact Context7-compatible library ID required to use this tool, UNLESS the user explicitly provides a library ID in the format '/org/project' or '/org/project/version' in their query. Use mode='code' (default) for API references and code examples, or mode='info' for conceptual guides, narrative information, and architectural questions.";
129
+
130
+ export { AGENT_PROMPT, type Context7ToolsConfig, GET_LIBRARY_DOCS_DESCRIPTION, RESOLVE_LIBRARY_DESCRIPTION, SYSTEM_PROMPT, getLibraryDocs, resolveLibrary };
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ import {
2
+ AGENT_PROMPT,
3
+ Context7Agent,
4
+ GET_LIBRARY_DOCS_DESCRIPTION,
5
+ RESOLVE_LIBRARY_DESCRIPTION,
6
+ SYSTEM_PROMPT,
7
+ getLibraryDocs,
8
+ resolveLibrary
9
+ } from "./chunk-AMSBQOUU.js";
10
+ export {
11
+ AGENT_PROMPT,
12
+ Context7Agent,
13
+ GET_LIBRARY_DOCS_DESCRIPTION,
14
+ RESOLVE_LIBRARY_DESCRIPTION,
15
+ SYSTEM_PROMPT,
16
+ getLibraryDocs,
17
+ resolveLibrary
18
+ };
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@upstash/context7-tools-ai-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Context7 tools for Vercel AI SDK",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js",
13
+ "require": "./dist/index.cjs"
14
+ },
15
+ "./agent": {
16
+ "types": "./dist/agent.d.ts",
17
+ "import": "./dist/agent.js",
18
+ "require": "./dist/agent.cjs"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "peerDependencies": {
25
+ "@upstash/context7-sdk": ">=0.1.0",
26
+ "ai": ">=5.0.0",
27
+ "zod": ">=3.24.0"
28
+ },
29
+ "devDependencies": {
30
+ "ai": "^5.0.0",
31
+ "zod": "^3.24.0",
32
+ "@ai-sdk/amazon-bedrock": "^3.0.55",
33
+ "@types/node": "^22.13.14",
34
+ "dotenv": "^17.2.3",
35
+ "tsup": "^8.5.1",
36
+ "typescript": "^5.8.2",
37
+ "vitest": "^4.0.13",
38
+ "@upstash/context7-sdk": "0.1.0"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/upstash/context7.git",
43
+ "directory": "packages/tools-ai-sdk"
44
+ },
45
+ "keywords": [
46
+ "context7",
47
+ "ai-sdk",
48
+ "vercel",
49
+ "documentation",
50
+ "agent",
51
+ "upstash"
52
+ ],
53
+ "author": "Upstash",
54
+ "license": "MIT",
55
+ "bugs": {
56
+ "url": "https://github.com/upstash/context7/issues"
57
+ },
58
+ "homepage": "https://github.com/upstash/context7#readme",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ },
62
+ "scripts": {
63
+ "build": "tsup",
64
+ "dev": "tsup --watch",
65
+ "test": "vitest run",
66
+ "typecheck": "tsc --noEmit",
67
+ "clean": "rm -rf dist"
68
+ }
69
+ }