chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 13:04:05 +08:00
commit 54d5556870
373 changed files with 47482 additions and 0 deletions
@@ -0,0 +1,202 @@
---
title: "Context7Agent"
sidebarTitle: "Context7Agent"
description: "Pre-built AI agent for documentation lookup workflows"
---
The `Context7Agent` class is a pre-configured AI agent that handles the complete documentation lookup workflow automatically. It combines both `resolveLibraryId` and `queryDocs` tools with an optimized system prompt.
## Usage
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
const agent = new Context7Agent({
model: anthropic("claude-sonnet-4-20250514"),
});
const { text } = await agent.generate({
prompt: "How do I use React Server Components?",
});
console.log(text);
```
## Configuration
```typescript
new Context7Agent(config?: Context7AgentConfig)
```
### Parameters
<ParamField path="config" type="Context7AgentConfig" optional>
Configuration options for the agent.
<Expandable title="properties">
<ParamField path="model" type="LanguageModel" optional>
Language model to use. Must be a LanguageModel instance from an AI SDK provider.
Examples:
- `anthropic('claude-sonnet-4-20250514')`
- `openai('gpt-5.2')`
- `google('gemini-1.5-pro')`
</ParamField>
<ParamField path="apiKey" type="string" optional>
Context7 API key. If not provided, uses the `CONTEXT7_API_KEY` environment variable.
</ParamField>
<ParamField path="system" type="string" optional>
Custom system prompt. Overrides the default `AGENT_PROMPT`.
</ParamField>
<ParamField path="stopWhen" type="StopCondition" optional default="stepCountIs(5)">
Condition for when the agent should stop. Defaults to stopping after 5 steps.
</ParamField>
</Expandable>
</ParamField>
### Returns
`Context7Agent` extends the AI SDK `Agent` class and provides `generate()` and `stream()` methods.
## Agent Workflow
The agent follows a structured multi-step workflow:
```mermaid
flowchart TD
A[User Query] --> B[Extract Library Name]
B --> C[Call resolveLibraryId]
C --> D{Results Found?}
D -->|Yes| E[Select Best Match]
D -->|No| F[Report No Results]
E --> G[Call queryDocs]
G --> H{Sufficient Context?}
H -->|Yes| I[Generate Response]
H -->|No| J[Fetch More Docs]
J --> H
I --> K[Return Answer with Examples]
```
### Step-by-Step
1. **Extract library name** - Identifies the library/framework from the user's query
2. **Resolve library** - Calls `resolveLibraryId` to find the Context7 library ID
3. **Select best match** - Analyzes results based on reputation, coverage, and relevance
4. **Fetch documentation** - Calls `queryDocs` with the selected library ID and user's query
5. **Query if needed** - Makes additional queries if initial context is insufficient
6. **Generate response** - Provides an answer with code examples from the documentation
## Examples
### Basic Usage
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
const agent = new Context7Agent({
model: anthropic("claude-sonnet-4-20250514"),
});
const { text } = await agent.generate({
prompt: "How do I set up authentication in Next.js?",
});
console.log(text);
```
### With OpenAI
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { openai } from "@ai-sdk/openai";
const agent = new Context7Agent({
model: openai("gpt-5.2"),
});
const { text } = await agent.generate({
prompt: "Explain Tanstack Query's useQuery hook",
});
```
### Streaming Responses
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
const agent = new Context7Agent({
model: anthropic("claude-sonnet-4-20250514"),
});
const { textStream } = await agent.stream({
prompt: "How do I create a Supabase Edge Function?",
});
for await (const chunk of textStream) {
process.stdout.write(chunk);
}
```
### Custom Configuration
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
import { stepCountIs } from "ai";
const agent = new Context7Agent({
model: anthropic("claude-sonnet-4-20250514"),
apiKey: process.env.CONTEXT7_API_KEY,
stopWhen: stepCountIs(8), // Allow more steps for complex queries
});
```
### Custom System Prompt
```typescript
import { Context7Agent, AGENT_PROMPT } from "@upstash/context7-tools-ai-sdk";
import { openai } from "@ai-sdk/openai";
const agent = new Context7Agent({
model: openai("gpt-5.2"),
system: `${AGENT_PROMPT}
Additional instructions:
- Always include TypeScript examples
- Mention version compatibility when relevant
- Suggest related documentation topics`,
});
```
## Comparison: Agent vs Tools
| Feature | Context7Agent | Individual Tools |
| ------------- | -------------------- | -------------------- |
| Setup | Single configuration | Configure each tool |
| Workflow | Automatic multi-step | Manual orchestration |
| System prompt | Optimized default | You provide |
| Customization | Limited | Full control |
| Best for | Quick integration | Custom workflows |
### When to Use the Agent
- Rapid prototyping
- Standard documentation lookup use cases
- When you want sensible defaults
### When to Use Individual Tools
- Custom agentic workflows
- Integration with other tools
- Fine-grained control over the process
- Custom system prompts with specific behavior
## Related
- [resolveLibraryId](/agentic-tools/ai-sdk/tools/resolve-library-id) - The library search tool used by the agent
- [queryDocs](/agentic-tools/ai-sdk/tools/query-docs) - The documentation fetch tool used by the agent
- [Getting Started](/agentic-tools/ai-sdk/getting-started) - Overview of the AI SDK integration
@@ -0,0 +1,162 @@
---
title: "Getting Started"
sidebarTitle: "Getting Started"
description: "Add Context7 documentation tools to your Vercel AI SDK applications"
---
`@upstash/context7-tools-ai-sdk` provides [Vercel AI SDK](https://sdk.vercel.ai/) compatible tools and agents that give your AI applications access to up-to-date library documentation.
When building AI-powered applications with the Vercel AI SDK, your models often need accurate information about libraries and frameworks. Instead of relying on potentially outdated training data, Context7 tools let your AI fetch current documentation on-demand, ensuring responses include correct API usage, current best practices, and working code examples.
The package gives you two ways to integrate:
1. **Individual tools** (`resolveLibraryId` and `queryDocs`) that you add to your existing `generateText` or `streamText` calls
2. **A pre-built agent** (`Context7Agent`) that handles the entire documentation lookup workflow automatically
Both approaches work with any AI provider supported by the Vercel AI SDK, including OpenAI, Anthropic, Google, and others.
## Installation
<CodeGroup>
```bash npm
npm install @upstash/context7-tools-ai-sdk
```
```bash pnpm
pnpm add @upstash/context7-tools-ai-sdk
```
```bash yarn
yarn add @upstash/context7-tools-ai-sdk
```
```bash bun
bun add @upstash/context7-tools-ai-sdk
```
</CodeGroup>
## Prerequisites
You'll need:
1. A Context7 API key from the [Context7 Dashboard](https://context7.com/dashboard)
2. An AI provider SDK (e.g., `@ai-sdk/openai`, `@ai-sdk/anthropic`)
## Configuration
Set your Context7 API key as an environment variable:
```bash
CONTEXT7_API_KEY=ctx7sk-...
```
The tools and agents will automatically use this key.
## Quick Start
### Using Tools with generateText
The simplest way to add documentation lookup to your AI application:
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "How do I create a server action in Next.js?",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
console.log(text);
```
### Using the Context7 Agent
For a more streamlined experience, use the pre-configured agent:
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
const agent = new Context7Agent({
model: anthropic("claude-sonnet-4-20250514"),
});
const { text } = await agent.generate({
prompt: "How do I use React Server Components?",
});
console.log(text);
```
### Using Tools with streamText
For streaming responses:
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { streamText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { textStream } = streamText({
model: openai("gpt-5.2"),
prompt: "Explain how to use Tanstack Query for data fetching",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
for await (const chunk of textStream) {
process.stdout.write(chunk);
}
```
## Explicit Configuration
You can also pass the API key directly if needed:
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
const tools = {
resolveLibraryId: resolveLibraryId({ apiKey: "your-api-key" }),
queryDocs: queryDocs({ apiKey: "your-api-key" }),
};
```
## How It Works
The tools follow a two-step workflow:
1. **`resolveLibraryId`** - Searches Context7's database to find the correct library ID for a given query (e.g., "react" → `/reactjs/react.dev`)
2. **`queryDocs`** - Fetches documentation for the resolved library using the user's query to retrieve relevant content
The AI model orchestrates these tools automatically based on the user's prompt, fetching relevant documentation before generating a response.
## Next Steps
<CardGroup cols={2}>
<Card
title="resolveLibraryId"
icon="magnifying-glass"
href="/agentic-tools/ai-sdk/tools/resolve-library-id"
>
Search for libraries and get Context7-compatible IDs
</Card>
<Card title="queryDocs" icon="book" href="/agentic-tools/ai-sdk/tools/query-docs">
Fetch documentation for a specific library
</Card>
<Card title="Context7Agent" icon="robot" href="/agentic-tools/ai-sdk/agents/context7-agent">
Use the pre-built documentation agent
</Card>
</CardGroup>
@@ -0,0 +1,196 @@
---
title: "queryDocs"
sidebarTitle: "queryDocs"
description: "Fetch up-to-date documentation for a specific library"
---
The `queryDocs` tool fetches documentation for a library using its Context7-compatible library ID and a query. This tool is typically called after `resolveLibraryId` has identified the correct library.
## Usage
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "How do I use React Server Components?",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
```
## Configuration
```typescript
queryDocs(config?: Context7ToolsConfig)
```
### Parameters
<ParamField path="config" type="Context7ToolsConfig" optional>
Configuration options for the tool.
<Expandable title="properties">
<ParamField path="apiKey" type="string" optional>
Context7 API key. If not provided, uses the `CONTEXT7_API_KEY` environment variable.
</ParamField>
</Expandable>
</ParamField>
### Returns
Returns an AI SDK `tool` that can be used with `generateText`, `streamText`, or agents.
## Tool Behavior
When the AI model calls this tool, it:
1. Takes a library ID and query from the model
2. Fetches documentation from Context7's API
3. Returns the documentation content
### Input Schema
The tool accepts the following inputs from the AI model:
<ParamField path="libraryId" type="string" required>
Context7-compatible library ID (e.g., `/reactjs/react.dev`, `/vercel/next.js`)
</ParamField>
<ParamField path="query" type="string" required>
The question or task you need help with, scoped to a single concept. Be specific and include relevant details, but keep each query to one topic — if the user's question spans multiple distinct concepts, make a separate call per concept instead of combining them, unless the question is about how the concepts interact. Good: "How to set up authentication with JWT in Express.js" or "React useEffect cleanup function examples". Bad (too vague): "auth" or "hooks". Bad (too broad): "routing and auth and caching in Next.js".
</ParamField>
### Output Format
On success, the tool returns the documentation as plain text, formatted for easy consumption by the AI model:
```
# Server Components
Server Components let you write UI that can be rendered and optionally cached on the server.
## Example
\`\`\`tsx
async function ServerComponent() {
const data = await fetchData();
return <div>{data}</div>;
}
\`\`\`
---
# Using Server Components with Client Components
You can import Server Components into Client Components...
```
#### On Failure
```
No documentation found for library "/invalid/library". This might have happened because you used an invalid Context7-compatible library ID. Use 'resolveLibraryId' to get a valid ID.
```
## Examples
### Basic Usage with Both Tools
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "Show me how to set up routing in Next.js App Router",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
// The model will:
// 1. Call resolveLibraryId to get the library ID
// 2. Call queryDocs({ libraryId: "/vercel/next.js", query: "routing in App Router" })
// 3. Generate a response using the fetched documentation
```
### With Custom Configuration
```typescript
import { queryDocs } from "@upstash/context7-tools-ai-sdk";
const tool = queryDocs({
apiKey: process.env.CONTEXT7_API_KEY,
});
```
### Direct Library ID (Skip resolveLibraryId)
If the user provides a library ID directly, the model can skip the resolution step:
```typescript
import { queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "Using /vercel/next.js, explain middleware",
tools: {
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(3),
});
// The model recognizes the /org/project format and calls queryDocs directly
```
### Multi-Step Documentation Lookup
For comprehensive documentation, the model can make multiple queries:
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
const { text } = await generateText({
model: anthropic("claude-sonnet-4-20250514"),
prompt: "Give me a comprehensive guide to Supabase authentication",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(8), // Allow more steps for multiple queries
});
// The model may call queryDocs multiple times with different queries
// to gather comprehensive documentation
```
## Version-Specific Documentation
Library IDs can include version specifiers:
```typescript
// Latest version
"/vercel/next.js";
// Specific version
"/vercel/next.js/v14.3.0-canary.87";
```
The model can request documentation for specific versions when the user asks about a particular version.
## Related
- [resolveLibraryId](/agentic-tools/ai-sdk/tools/resolve-library-id) - Search for libraries and get their IDs
- [Context7Agent](/agentic-tools/ai-sdk/agents/context7-agent) - Pre-built agent that handles the full workflow
@@ -0,0 +1,174 @@
---
title: "resolveLibraryId"
sidebarTitle: "resolveLibraryId"
description: "Search for libraries and resolve them to Context7-compatible IDs"
---
The `resolveLibraryId` tool searches Context7's library database and returns matching results with their Context7-compatible library IDs. This is typically the first step in a documentation lookup workflow.
## Usage
```typescript
import { resolveLibraryId } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "Find documentation for React hooks",
tools: {
resolveLibraryId: resolveLibraryId(),
},
stopWhen: stepCountIs(3),
});
```
## Configuration
```typescript
resolveLibraryId(config?: Context7ToolsConfig)
```
### Parameters
<ParamField path="config" type="Context7ToolsConfig" optional>
Configuration options for the tool.
<Expandable title="properties">
<ParamField path="apiKey" type="string" optional>
Context7 API key. If not provided, uses the `CONTEXT7_API_KEY` environment variable.
</ParamField>
</Expandable>
</ParamField>
### Returns
Returns an AI SDK `tool` that can be used with `generateText`, `streamText`, or agents.
## Tool Behavior
When the AI model calls this tool, it:
1. Takes a `query` and `libraryName` parameter from the model
2. Searches Context7's database for matching libraries
3. Returns formatted results including:
- Library ID (e.g., `/reactjs/react.dev`)
- Title and description
- Number of code snippets available
- Source reputation score
- Available versions
### Input Schema
The tool accepts the following input from the AI model:
<ParamField path="query" type="string" required>
The user's original question or task. This is used to rank library results by relevance to what the user is trying to accomplish.
</ParamField>
<ParamField path="libraryName" type="string" required>
Library name to search for (e.g., "react", "next.js", "vue")
</ParamField>
### Output Format
On success, the tool returns the search results as plain text, formatted for easy consumption by the AI model:
```
- Title: React Documentation
- Context7-compatible library ID: /reactjs/react.dev
- Description: The library for web and native user interfaces
- Code Snippets: 1250
- Source Reputation: High
- Benchmark Score: 98
- Versions: 19.0.0, 18.3.1, 18.2.0
----------
- Title: React Native
- Context7-compatible library ID: /facebook/react-native
- Description: A framework for building native applications using React
- Code Snippets: 890
- Source Reputation: High
- Benchmark Score: 95
- Versions: 0.76.0, 0.75.4
```
On failure:
```
No libraries found matching "unknown-lib". Try a different search term or check the library name.
```
## Examples
### Basic Usage
```typescript
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { text, toolCalls } = await generateText({
model: openai("gpt-5.2"),
prompt: "What libraries are available for React?",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
// The model will call resolveLibraryId and receive a list of matching libraries
console.log(text);
```
### With Custom API Key
```typescript
import { resolveLibraryId } from "@upstash/context7-tools-ai-sdk";
const tool = resolveLibraryId({
apiKey: process.env.CONTEXT7_API_KEY,
});
```
### Inspecting Tool Calls
```typescript
import { resolveLibraryId } from "@upstash/context7-tools-ai-sdk";
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
const { toolCalls, toolResults } = await generateText({
model: openai("gpt-5.2"),
prompt: "Find the official Next.js documentation",
tools: {
resolveLibraryId: resolveLibraryId(),
},
stopWhen: stepCountIs(3),
});
// See what the model searched for
for (const call of toolCalls) {
console.log("Searched for:", call.input.libraryName);
}
// See the results
for (const result of toolResults) {
console.log("Found:", result.output);
}
```
## Selection Guidance
The tool's description instructs the AI model to select libraries based on:
1. **Name similarity** - Exact matches are prioritized
2. **Description relevance** - How well the description matches the query intent
3. **Documentation coverage** - Libraries with more code snippets are preferred
4. **Source reputation** - High/Medium reputation sources are more authoritative
5. **Benchmark score** - Quality indicator (100 is the highest)
## Related
- [queryDocs](/agentic-tools/ai-sdk/tools/query-docs) - Fetch documentation using the resolved library ID
- [Context7Agent](/agentic-tools/ai-sdk/agents/context7-agent) - Pre-built agent that handles the full workflow
+139
View File
@@ -0,0 +1,139 @@
---
title: "Overview"
sidebarTitle: "Overview"
description: "Build AI agents with up-to-date library documentation"
---
# Agentic Tools
Context7 provides tools and integrations that give your AI agents access to accurate, up-to-date library documentation. Instead of relying on potentially outdated training data, your agents can fetch real-time documentation to answer questions and generate code.
## Why Agentic Tools?
AI agents often struggle with:
- **Outdated knowledge** - Training data becomes stale, leading to deprecated API usage
- **Hallucinated APIs** - Models confidently suggest methods that don't exist
- **Version mismatches** - Code examples from old versions that no longer work
Context7's agentic tools solve these problems by giving your agents direct access to current documentation during inference.
## Available Integrations
<CardGroup cols={1}>
<Card
title="Vercel AI SDK"
icon="wand-magic-sparkles"
href="/agentic-tools/ai-sdk/getting-started"
>
Add Context7 tools to your AI SDK workflows with `generateText`, `streamText`, or use the
pre-built `Context7Agent` for automatic documentation lookup.
</Card>
<Card title="TypeScript SDK" icon="js" href="/sdks/ts/getting-started">
Call Context7 directly from any TypeScript or Node.js app.
</Card>
<Card title="MCP Server" icon="plug" href="/resources/all-clients">
Connect Context7's MCP server to any agent or editor.
</Card>
</CardGroup>
## How It Works
```mermaid
sequenceDiagram
participant User
participant Agent
participant Context7
participant Docs
User->>Agent: "How do I use React Server Components?"
Agent->>Context7: resolveLibraryId(query: "React Server Components", libraryName: "react")
Context7-->>Agent: Library ID: /reactjs/react.dev
Agent->>Context7: queryDocs(libraryId: "/reactjs/react.dev", query: "server components")
Context7->>Docs: Fetch latest documentation
Docs-->>Context7: Current docs with examples
Context7-->>Agent: Documentation content
Agent->>User: Answer with accurate, up-to-date code examples
```
## Use Cases
<AccordionGroup>
<Accordion title="Documentation-Aware Chatbots" icon="comments">
Build chatbots that answer framework questions with accurate, version-specific information:
```typescript
import { generateText, stepCountIs } from "ai";
import { openai } from "@ai-sdk/openai";
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
const { text } = await generateText({
model: openai("gpt-5.2"),
prompt: "How do I set up authentication in Next.js 15?",
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
```
</Accordion>
<Accordion title="Code Generation Pipelines" icon="code">
Ensure generated code uses current APIs and best practices:
```typescript
import { Context7Agent } from "@upstash/context7-tools-ai-sdk";
import { anthropic } from "@ai-sdk/anthropic";
const agent = new Context7Agent({
model: anthropic("claude-sonnet-4-20250514"),
});
const { text } = await agent.generate({
prompt: "Generate a Supabase Edge Function that handles webhooks",
});
```
</Accordion>
<Accordion title="Code Review Agents" icon="magnifying-glass-chart">
Build code review agents that verify implementations against current API documentation:
```typescript
import { generateText, stepCountIs } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
import { resolveLibraryId, queryDocs } from "@upstash/context7-tools-ai-sdk";
const codeToReview = `
const { data } = await supabase
.from('users')
.select('*')
.eq('id', userId)
.single();
`;
const { text } = await generateText({
model: anthropic("claude-sonnet-4-20250514"),
prompt: `Review this Supabase code for correctness and best practices:
${codeToReview}
Check against the latest Supabase documentation.`,
tools: {
resolveLibraryId: resolveLibraryId(),
queryDocs: queryDocs(),
},
stopWhen: stepCountIs(5),
});
// Agent fetches current Supabase docs to verify:
// - Correct method signatures
// - Deprecated patterns
// - Security best practices
// - Error handling recommendations
```
</Accordion>
</AccordionGroup>