diff --git a/examples/research/README-youcom.md b/examples/research/README-youcom.md new file mode 100644 index 000000000..a3dca3efb --- /dev/null +++ b/examples/research/README-youcom.md @@ -0,0 +1,197 @@ +# You.com Search Integration + +This directory contains examples demonstrating how to integrate You.com's search API with Deep Agents for enhanced web research capabilities. + +## Overview + +The You.com search integration provides high-quality web search results with source citations, offering an alternative to other search providers. It supports both authenticated and keyless usage modes. + +## Files + +- `tools/youcom-search.ts` - You.com search tool implementation +- `youcom-search-agent.ts` - Simple example agent using You.com search +- `research-agent.ts` - Enhanced research agent with both Tavily and You.com search options + +## Setup + +### Option 1: Keyless Mode (Basic) + +The You.com search tool works without any API key for basic search functionality: + +```typescript +import { youcomSearch } from "./tools/youcom-search.js"; + +// No environment variables needed for basic usage +const agent = createDeepAgent({ + model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }), + tools: [youcomSearch], +}); +``` + +### Option 2: Authenticated Mode (Enhanced) + +For enhanced features and higher rate limits, add your You.com API key: + +```bash +# Add to your .env file +YDC_API_KEY=your_youcom_api_key_here +``` + +Get your API key from [You.com API](https://api.you.com/?utm_source=deepagents&utm_medium=integration&utm_campaign=search_tool). + +## Usage Examples + +### Basic Web Search + +```typescript +import { createDeepAgent } from "deepagents"; +import { youcomSearch } from "./tools/youcom-search.js"; + +const agent = createDeepAgent({ + model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }), + tools: [youcomSearch], + systemPrompt: "You are a research assistant with web search capabilities.", +}); + +const result = await agent.invoke({ + messages: [new HumanMessage("What are the latest developments in AI?")], +}); +``` + +### Multi-Tool Research Agent + +```typescript +import { youcomSearch } from "./tools/youcom-search.js"; +import { internetSearch } from "./research-agent.js"; // Tavily search + +const researchAgent = createDeepAgent({ + model: new ChatAnthropic({ model: "claude-sonnet-4-20250514" }), + tools: [internetSearch, youcomSearch], // Multiple search providers + systemPrompt: `You have access to multiple search tools: + - internet_search: Tavily search with topic filtering + - youcom_search: You.com search with high-quality results`, +}); +``` + +### Tool Parameters + +The `youcom_search` tool accepts these parameters: + +- `query` (string, required): The search query +- `maxResults` (number, optional, default: 5): Maximum number of results (1-20) +- `includeRawContent` (boolean, optional, default: false): Include raw content (not currently implemented) + +## Features + +- **High-quality results**: You.com's search API provides curated, relevant results +- **Source citations**: Results include titles, URLs, and snippets +- **Flexible authentication**: Works with or without API keys +- **Error handling**: Graceful handling of rate limits, authentication errors, and API issues +- **TypeScript support**: Full type safety with Zod schema validation + +## Error Handling + +The tool handles common error scenarios: + +- **401 Unauthorized**: Invalid or missing API key +- **429 Rate Limited**: Too many requests (try again later or add API key) +- **402 Payment Required**: Quota exceeded (add API key for higher limits) +- **Network errors**: Connection timeouts and other network issues + +## Integration with Deep Agents + +The You.com search tool follows Deep Agents conventions: + +- Uses the standard LangChain `tool()` function +- Includes Zod schema for parameter validation +- Returns formatted text results compatible with agent reasoning +- Handles errors gracefully without breaking agent workflows + +## Running Examples + +```bash +# Install dependencies +pnpm install + +# Set up environment (optional for keyless mode) +cp .env.example .env +# Edit .env to add YDC_API_KEY if desired + +# Run the You.com search example +npx tsx examples/research/youcom-search-agent.ts + +# Run the enhanced research agent with multiple search tools +npx tsx examples/research/research-agent.ts +``` + +## API Reference + +### You.com Search API + +- **Endpoint**: `https://api.you.com/v1/agents/search` +- **Authentication**: Bearer token (optional) +- **Rate Limits**: Higher limits with API key +- **Documentation**: [You.com API Docs](https://documentation.you.com/?utm_source=deepagents&utm_medium=integration&utm_campaign=search_tool) + +### Tool Schema + +```typescript +{ + query: string; // Search query + maxResults?: number; // Max results (1-20, default: 5) + includeRawContent?: boolean; // Include raw content (default: false) +} +``` + +### Response Format + +The tool returns formatted search results as text: + +``` +Found 5 search results for "AI developments": + +1. **Latest AI Breakthroughs in 2024** + URL: https://example.com/ai-breakthroughs + Recent advances in AI include improved language models... + +2. **AI Research Trends** + URL: https://example.com/ai-trends + Researchers are focusing on multimodal AI systems... +``` + +## Best Practices + +1. **Use appropriate maxResults**: Start with 5 results, adjust based on needs +2. **Handle errors gracefully**: The tool returns error messages as strings for agent processing +3. **Combine with other tools**: Use alongside filesystem, memory, and other research tools +4. **API key management**: Use environment variables, never hardcode keys +5. **Rate limiting**: Be mindful of API limits, especially in keyless mode + +## Troubleshooting + +### Common Issues + +**"No search results found"** +- Try rephrasing the query +- Check internet connectivity +- Verify the query is not too specific + +**"Rate limit exceeded"** +- Add a YDC_API_KEY for higher limits +- Wait before retrying +- Reduce search frequency in agent workflows + +**"API authentication failed"** +- Verify YDC_API_KEY is correct +- Check environment variable is loaded +- Ensure API key has proper permissions + +### Support + +For issues with the You.com API: +- [You.com API Documentation](https://documentation.you.com/?utm_source=deepagents&utm_medium=integration&utm_campaign=search_tool) +- [You.com Support](https://about.you.com/contact/?utm_source=deepagents&utm_medium=integration&utm_campaign=search_tool) + +For Deep Agents integration issues: +- [Deep Agents GitHub Issues](https://github.com/langchain-ai/deepagentsjs/issues) +- [Deep Agents Documentation](https://docs.langchain.com/oss/javascript/deepagents) \ No newline at end of file diff --git a/examples/research/research-agent.ts b/examples/research/research-agent.ts index 9e731c1db..53df9b3ba 100644 --- a/examples/research/research-agent.ts +++ b/examples/research/research-agent.ts @@ -5,6 +5,7 @@ import { TavilySearch } from "@langchain/tavily"; import { ChatAnthropic } from "@langchain/anthropic"; import { createDeepAgent, type SubAgent } from "deepagents"; +import { youcomSearch } from "./tools/youcom-search.js"; type Topic = "general" | "news" | "finance"; @@ -74,7 +75,7 @@ const researchSubAgent: SubAgent = { description: "Used to research more in depth questions. Only give this researcher one topic at a time. Do not pass multiple sub questions to this researcher. Instead, you should break down a large topic into the necessary components, and then call multiple research agents in parallel, one for each sub question.", systemPrompt: subResearchPrompt, - tools: [internetSearch], + tools: [internetSearch, youcomSearch], }; const subCritiquePrompt = `You are a dedicated editor. You are being tasked to critique a report. @@ -191,10 +192,13 @@ Format the report in clear markdown with proper structure and include source ref You have access to a few tools. -## \`internet_search\` +## internet_search -Use this to run an internet search for a given query. You can specify the number of results, the topic, and whether raw content should be included. -`; +Use this to run an internet search for a given query using Tavily. You can specify the number of results, the topic, and whether raw content should be included. + +## youcom_search + +Use this to run an internet search for a given query using You.com's search API. Provides high-quality search results with source citations. You can specify the number of results. Requires YDC_API_KEY environment variable for authenticated access, but also works without it in keyless mode.`; // Create the agent export const agent = createDeepAgent({ @@ -203,7 +207,7 @@ export const agent = createDeepAgent({ temperature: 0, }), - tools: [internetSearch], + tools: [internetSearch, youcomSearch], systemPrompt: researchInstructions, subagents: [critiqueSubAgent, researchSubAgent], }); @@ -219,16 +223,16 @@ export const agent = createDeepAgent({ // console.log("🎉 Finished!"); // console.log( -// `\n\nAgent ToDo List:\n${result.todos.map((todo) => ` - ${todo.content} (${todo.status})`).join("\n")}` +// "\\n\\nAgent ToDo List:\\n" + result.todos.map((todo) => " - " + todo.content + " (" + todo.status + ")").join("\\n") // ); // console.log( -// `\n\nAgent Files:\n${Object.entries(result.files) -// .map(([key, value]) => ` - ${key}: ${value}`) -// .join("\n")}` +// "\\n\\nAgent Files:\\n" + Object.entries(result.files) +// .map(([key, value]) => " - " + key + ": " + value) +// .join("\\n") // ); // } // // Run if this file is executed directly -// if (import.meta.url === `file://${process.argv[1]}`) { +// if (import.meta.url === "file://" + process.argv[1]) { // main(); // } diff --git a/examples/research/tools/youcom-search.ts b/examples/research/tools/youcom-search.ts new file mode 100644 index 000000000..91f60ae6d --- /dev/null +++ b/examples/research/tools/youcom-search.ts @@ -0,0 +1,132 @@ +import { z } from "zod"; +import { tool } from "langchain"; + +/** + * You.com web search tool for Deep Agents + * + * Provides web search capabilities using the You.com Search API. + * Supports both authenticated (with YDC_API_KEY) and keyless usage. + */ + +interface YouComSearchResult { + title: string; + url: string; + snippet: string; +} + +interface YouComSearchResponse { + results: { + web?: YouComSearchResult[]; + }; +} + +/** + * You.com web search tool + */ +export const youcomSearch = tool( + async ({ + query, + maxResults = 5, + includeRawContent = false, + }: { + query: string; + maxResults?: number; + includeRawContent?: boolean; + }) => { + try { + const apiKey = process.env.YDC_API_KEY; + const baseUrl = "https://api.you.com/v1/agents/search"; + + const params = new URLSearchParams({ + query, + count: maxResults.toString(), + }); + + const headers: Record = { + "Content-Type": "application/json", + "User-Agent": "deepagents-youcom-integration/1.0", + }; + + // Add API key if available + if (apiKey) { + headers.Authorization = `Bearer ${apiKey}`; + } + + const response = await fetch(`${baseUrl}?${params}`, { + method: "GET", + headers, + }); + + if (!response.ok) { + if (response.status === 401) { + throw new Error( + "You.com API authentication failed. Please check your YDC_API_KEY environment variable.", + ); + } else if (response.status === 429) { + throw new Error( + "You.com API rate limit exceeded. Please try again later or add a YDC_API_KEY for higher limits.", + ); + } else if (response.status === 402) { + throw new Error( + "You.com API quota exceeded. Please add a YDC_API_KEY or try again later.", + ); + } + throw new Error( + `You.com API error: ${response.status} ${response.statusText}`, + ); + } + + const data: YouComSearchResponse = await response.json(); + const webResults = data.results?.web || []; + + if (webResults.length === 0) { + return "No search results found for the given query."; + } + + // Format results for the agent + const formattedResults = webResults + .slice(0, maxResults) + .map((result, index) => { + let formattedResult = `${index + 1}. **${result.title}**\n URL: ${result.url}`; + + if (result.snippet) { + formattedResult += `\n ${result.snippet}`; + } + + return formattedResult; + }) + .join("\n\n"); + + const summary = `Found ${webResults.length} search results for "${query}": + +${formattedResults}`; + + return summary; + } catch (error) { + if (error && typeof error === "object" && "message" in error) { + return `Search error: ${(error as Error).message}`; + } + return `Search error: An unexpected error occurred while searching.`; + } + }, + { + name: "youcom_search", + description: + "Search the web using You.com's search API. Provides current web information with high-quality results and source citations.", + schema: z.object({ + query: z.string().describe("The search query to find information about"), + maxResults: z + .number() + .optional() + .default(5) + .describe("Maximum number of search results to return (1-20)"), + includeRawContent: z + .boolean() + .optional() + .default(false) + .describe( + "Whether to include raw content from pages (currently not implemented)", + ), + }), + }, +); diff --git a/examples/research/youcom-search-agent.ts b/examples/research/youcom-search-agent.ts new file mode 100644 index 000000000..9e109039b --- /dev/null +++ b/examples/research/youcom-search-agent.ts @@ -0,0 +1,49 @@ +import "dotenv/config"; +import { ChatAnthropic } from "@langchain/anthropic"; +import { createDeepAgent } from "deepagents"; +import { youcomSearch } from "./tools/youcom-search.js"; + +/** + * Simple You.com search agent example + * + * This example demonstrates how to use the You.com search tool + * with Deep Agents for web research capabilities. + */ + +const searchInstructions = `You are a helpful research assistant with web search capabilities. + +You have access to the You.com search tool which provides high-quality web search results. +Use it to find current information on topics the user asks about. + +When providing search results: +1. Summarize the key findings +2. Include relevant quotes and facts +3. Cite sources with URLs when possible +4. Provide balanced, comprehensive information + +The You.com search tool works with or without an API key: +- With YDC_API_KEY: Enhanced features and higher rate limits +- Without API key: Basic search functionality in keyless mode`; + +// Create the agent with You.com search +export const youcomAgent = createDeepAgent({ + model: new ChatAnthropic({ + model: "claude-sonnet-4-20250514", + temperature: 0, + }), + tools: [youcomSearch], + systemPrompt: searchInstructions, +}); + +// Example usage (uncomment to test) +// async function main() { +// const result = await youcomAgent.invoke({ +// messages: [new HumanMessage("What are the latest developments in AI agents?")], +// }); +// +// console.log("Agent response:", result.messages[result.messages.length - 1].content); +// } +// +// if (import.meta.url === `file://${process.argv[1]}`) { +// main().catch(console.error); +// }