### API Parameter Combination Example Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/prompting.md Shows a practical example of how to combine a search query with various API parameters to refine search results, including search type, included sources, date range, relevance threshold, and number of results. ```javascript { query: "mRNA vaccine cancer immunotherapy clinical trials", search_type: "proprietary", included_sources: ["pubmed", "biorxiv"], start_date: "2024-01-01", relevance_threshold: 0.7, max_num_results: 15 } ``` -------------------------------- ### Structured Output Example for Search API Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md An example demonstrating how to define a structured output schema for the search API. This allows for formatted responses tailored to specific data extraction needs. ```javascript structured_output: { type: "object", properties: { summary: { type: "string" }, key_points: { type: "array", items: { type: "string" } }, confidence: { type: "number" } } } ``` -------------------------------- ### Example Query Length Optimization Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/prompting.md Demonstrates how to shorten a lengthy, unfocused query into a concise and effective one by removing filler words and focusing on key terms. ```plaintext # Too long "I'm looking for information about the latest developments in artificial development, specifically focusing on large language models and their applications in healthcare settings, preferably from recent peer-reviewed academic papers published in 2024" # Better "large language models healthcare applications 2024 peer-reviewed" ``` -------------------------------- ### Install and Initialize Valyu SDK (JavaScript/TypeScript) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/SKILL.md Installs the `valyu-js` SDK using npm or pnpm and demonstrates how to initialize the Valyu client with an API key. ```bash npm install valyu-js # or pnpm add valyu-js ``` ```typescript import { Valyu } from 'valyu-js'; const valyu = new Valyu(process.env.VALYU_API_KEY); ``` -------------------------------- ### Install and Initialize Valyu SDK (Python) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/SKILL.md Installs the `valyu` Python package using pip or uv and shows how to initialize the Valyu client with an API key. ```bash pip install valyu # or uv add valyu ``` ```python from valyu import Valyu import os valyu = Valyu(api_key=os.environ.get("VALYU_API_KEY")) ``` -------------------------------- ### Query Examples (Text) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/SKILL.md Illustrates effective query construction by contrasting 'bad' and 'good' examples. It emphasizes specificity, domain terminology, constraints, and source types for better results. ```text BAD: "I want to know about AI" GOOD: "transformer attention mechanism survey 2024" BAD: "Apple financial information" GOOD: "Apple revenue growth Q4 2024 earnings SEC filing" BAD: "gene editing research" GOOD: "CRISPR off-target effects therapeutic applications 2024" ``` -------------------------------- ### Customize AI Answer with System Instructions (Python) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/answer-recipes/answer-with-custom-instructions.md This Python example demonstrates using the `system_instructions` parameter with the Valyu Python SDK to control AI output. It instructs the AI to prioritize commercial impact and present findings in bullet points. Ensure the 'valyu' package is installed. ```python from valyu import Valyu valyu = Valyu() data = valyu.answer( query="climate change research", system_instructions="Focus on practical applications and commercial impact. Summarise key findings as bullet points." ) print(data["contents"]) ``` -------------------------------- ### Valyu Financial Analysis Workflow Example Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/recipes.md Illustrates a financial analysis workflow using Valyu CLI commands. This specific example focuses on retrieving SEC filings for a given company and year. ```bash # 1. Get SEC filings scripts/valyu search sec "Apple 10-K 2024" 10 ``` -------------------------------- ### Clone and Configure Python Environment Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/mcp-desktop.md Clones the Valyu MCP repository and sets up a Python virtual environment. It installs necessary dependencies using pip. Ensure Python 3.10+ is installed. ```bash git clone https://github.com/valyuAI/valyu-mcp.git cd valyu-mcp # macOS/Linux python -m venv .venv source .venv/bin/activate # Windows python -m venv .venv .venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Install Valyu Claude Agent SDK Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/claude-agent-sdk.md Instructions for cloning the repository, navigating to the directory, and installing dependencies using npm. It also shows how to configure API credentials in a .env file. ```bash git clone https://github.com/GhouI/valyu-claude-agent-sdk.git cd valyu-claude-agent-sdk npm install --legacy-peer-deps ``` ```bash VALYU_API_KEY=your-valyu-api-key-here ``` -------------------------------- ### Install Valyu and Anthropic Libraries Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/anthropic.md Installs the necessary Python libraries for Valyu and Anthropic integration. Also shows how to set the required API keys as environment variables. ```bash pip install valyu anthropic export VALYU_API_KEY="your-valyu-api-key" export ANTHROPIC_API_KEY="your-anthropic-api-key" ``` -------------------------------- ### List Datasources API Request Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md An example of a GET request to the Datasources API to list all available data sources. An optional category parameter can be used for filtering. ```http GET /v1/datasources GET /v1/datasources?category=healthcare ``` -------------------------------- ### Install Valyu AI SDK Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/vercel-ai-sdk.md Installs the Valyu AI SDK using npm. This is the first step to integrate Valyu's search functionalities into your project. ```bash npm install @valyu/ai-sdk ``` -------------------------------- ### Customize AI Answer with System Instructions (TypeScript) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/answer-recipes/answer-with-custom-instructions.md This snippet shows how to use the `systemInstructions` parameter in the Valyu JS SDK to guide the AI's response. It specifies focusing on practical applications and commercial impact, and summarizing key findings as bullet points. Ensure you have the 'valyu-js' package installed and replace 'YOUR_VALYU_API_KEY_HERE' with your actual API key. ```typescript import { Valyu } from "valyu-js"; const valyu = new Valyu(YOUR_VALYU_API_KEY_HERE); const data = await valyu.answer({ query: "climate change research", systemInstructions: "Focus on practical applications and commercial impact. Summarise key findings as bullet points." }); console.log(data.contents); ``` -------------------------------- ### Install LangChain-Valyu Package Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/langchain.md Installs the necessary Valyu package for LangChain integration. This is the first step to using Valyu tools within your LangChain projects. ```bash pip install -U langchain-valyu ``` -------------------------------- ### Install Google Gemini and Requests Libraries Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/google.md Installs the necessary Python libraries for interacting with the Google Generative AI API and making HTTP requests. These are essential for the Valyu integration. ```bash pip install google-generativeai requests ``` -------------------------------- ### Generate AI Answer using Valyu CLI Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/answer-recipes/basic-answer.md This command-line interface (CLI) example shows how to use the Valyu script to get an AI-generated answer directly from the terminal. It takes the user's query as a command-line argument, processes it using the configured Valyu service, and outputs the resulting answer. ```bash scripts/valyu answer "What are the latest developments in quantum computing?" ``` -------------------------------- ### Financial Agent Usage Example Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/anthropic.md Demonstrates how to create and use a financial agent to analyze a list of assets. The agent takes a list of strings (asset names) and returns an analysis. ```python financial_agent = create_financial_agent() analysis = financial_agent(["Bitcoin", "Ethereum", "Tesla"]) print(analysis) ``` -------------------------------- ### Install Valyu Search Plugin Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/claude-code-plugin.md Commands to install the Valyu Search Plugin from the plugin marketplace. This involves adding the marketplace and then installing the specific plugin. ```bash /plugin marketplace add valyuAI/valyu-search-plugin /plugin install valyu-search-plugin@valyu-marketplace ``` -------------------------------- ### Install Valyu and OpenAI Libraries Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/openai.md Installs the necessary Python packages for Valyu and OpenAI integration. Ensure you have pip installed. ```bash pip install valyu openai ``` -------------------------------- ### Install Valyu Agent Skills CLI Source: https://github.com/valyuai/skills/blob/main/README.md Installs the Valyu agent skills using npm. This command adds the necessary tools to your environment for interacting with Valyu's API through agent skills. ```bash npx skills add valyuAI/skills ``` -------------------------------- ### Content Extraction CLI Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/content-recipes/basic-content-extraction-from-web-with-summary.md Provides examples of using the Valyu CLI for content extraction and summarization. ```APIDOC ## CLI Commands ### Basic Summary ```bash scripts/valyu contents "https://example.com" --summary ``` ### Custom Summary Instructions ```bash scripts/valyu contents "https://example.com" --summary "Key points in 3 bullets" ``` ### Description These commands utilize the Valyu CLI to extract content from a given URL and generate summaries. The `--summary` flag enables basic summarization, while providing a string argument to `--summary` allows for custom summarization instructions. ``` -------------------------------- ### LangChain Agent with ValyuSearchTool and Anthropic Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/langchain.md Shows how to create a LangChain ReAct agent using ValyuSearchTool and Anthropic's ChatAnthropic model. This example demonstrates streaming agent responses to a user query. ```python import os from langchain_valyu import ValyuSearchTool from langchain_anthropic import ChatAnthropic from langgraph.prebuilt import create_react_agent from langchain_core.messages import HumanMessage os.environ["VALYU_API_KEY"] = "your-valyu-api-key" os.environ["ANTHROPIC_API_KEY"] = "your-anthropic-api-key" llm = ChatAnthropic(model="claude-sonnet-4-20250514") valyu_search_tool = ValyuSearchTool() agent = create_react_agent(llm, [valyu_search_tool]) user_input = "What are the key factors driving recent stock market volatility?" for step in agent.stream( {"messages": [HumanMessage(content=user_input)]}, stream_mode="values", ): step["messages"][-1].pretty_print() ``` -------------------------------- ### Search with Collections in Valyu (Python) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/search-recipes/using-collections-to-search.md Illustrates how to integrate Valyu collections into Python searches. The examples show referencing a collection using the 'collection:' prefix and merging collections with additional sources. ```python from valyu import Valyu valyu = Valyu() # Use a saved collection response = valyu.search( query="market trends 2024", search_type="all", included_sources=["collection:my-finance-sources"] ) # Combine collection with other sources combined = valyu.search( query="healthcare innovation", search_type="all", included_sources=[ "collection:medical-research", "techcrunch.com", "valyu/valyu-patents" ] ) ``` -------------------------------- ### Install LangGraph and Langchain-Anthropic Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/langchain.md Installs additional packages required for building LangChain agents that use Anthropic's models and the LangGraph library for agentic workflows. These are dependencies for advanced agent examples. ```bash pip install langchain-anthropic langgraph ``` -------------------------------- ### Search Academic Papers with Valyu API (TypeScript) Source: https://context7.com/valyuai/skills/llms.txt Illustrates how to search for academic papers from specific sources like arXiv, PubMed, and bioRxiv using the Valyu JavaScript SDK. This example shows how to filter by included sources and set a start date for the search. It also includes an example of cross-disciplinary research by including both academic and general web sources. ```typescript import { Valyu } from "valyu-js"; const valyu = new Valyu(process.env.VALYU_API_KEY); // Search specific academic databases const response = await valyu.search({ query: "CRISPR gene editing therapeutic applications", searchType: "proprietary", includedSources: ["valyu/valyu-arxiv", "valyu/valyu-pubmed", "valyu/valyu-biorxiv"], maxNumResults: 20, startDate: "2024-01-01" }); // Cross-disciplinary research const crossDisciplinary = await valyu.search({ query: "transformer architecture neural networks", searchType: "proprietary", includedSources: ["valyu/valyu-arxiv", "nature.com", "science.org"], maxNumResults: 15 }); console.log(`Found ${response.results.length} papers`); response.results.forEach(paper => { console.log(`- ${paper.title} (${paper.publicationDate})`); }); ``` -------------------------------- ### Valyu Plugin Example Commands Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/claude-code-plugin.md Demonstrates various ways to use the Valyu plugin, including web searches, financial data retrieval, academic paper searches, general questions, content extraction from URLs, and initiating/checking deep research tasks. ```bash Valyu(web, "AI developments 2025", 10) Valyu(finance, "Apple Q4 2024 earnings", 8) Valyu(paper, "transformer neural networks", 15) Valyu(answer, "What is quantum computing?") Valyu(contents, "https://example.com/article") Valyu(deepresearch, create, "AI market trends 2025") Valyu(deepresearch, status, "task-id-here") ``` -------------------------------- ### DeepResearch API Task Creation Request Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md Example of a POST request to create a deep research task. It includes the research query, desired model, output format, and source filtering options. ```json { "query": "AI market trends 2024", "model": "standard", "output_format": "markdown", "included_sources": [], "excluded_sources": [], "start_date": null, "end_date": null } ``` -------------------------------- ### Financial Research Assistant Agent with Valyu Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/langchain.md An example of a specialized LangChain agent designed for financial research. It uses ValyuSearchTool and Anthropic's LLM, with a system message guiding the agent to focus on financial data and cite sources. ```python from langchain_valyu import ValyuSearchTool from langchain_anthropic import ChatAnthropic from langgraph.prebuilt import create_react_agent from langchain_core.messages import HumanMessage, SystemMessage financial_llm = ChatAnthropic(model="claude-sonnet-4-20250514") valyu_tool = ValyuSearchTool() financial_agent = create_react_agent(financial_llm, [valyu_tool]) query = "What are the latest developments in cryptocurrency regulation?" system_context = SystemMessage(content="""You are a financial research assistant. Use Valyu to search for: - Real-time market data and news - Academic research on financial models - Economic indicators and analysis Always cite your sources and provide context about data recency.""" for step in financial_agent.stream( {"messages": [system_context, HumanMessage(content=query)]}, stream_mode="values", ): step["messages"][-1].pretty_print() ``` -------------------------------- ### Valyu Python SDK Usage Examples Source: https://context7.com/valyuai/skills/llms.txt This Python snippet showcases various functionalities of the Valyu Python SDK, including performing searches, extracting content from URLs, getting answers with citations, and initiating deep research tasks. It requires the VALYU_API_KEY environment variable. ```python from valyu import Valyu import os valyu = Valyu(api_key=os.environ.get("VALYU_API_KEY")) # Search response = valyu.search( query="latest developments in quantum computing", search_type="all", max_num_results=10 ) for result in response["results"]: print(f"Title: {result['title']}") print(f"URL: {result['url']}") print(f"Content: {result['content'][:200]}...") # Contents extraction data = valyu.contents( urls=["https://example.com/article"], response_length="medium", extract_effort="auto" ) # Answer with citations answer = valyu.answer( query="What is quantum computing?", fast_mode=True ) print(answer["contents"]) # DeepResearch task = valyu.deepresearch.create( input="AI market trends 2024", model="standard" ) result = valyu.deepresearch.wait( task.deepresearch_id, poll_interval=5, max_wait_time=1800 ) if result.status == "completed": print(result.output) ``` -------------------------------- ### Datasource Response Structure (JSON) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md This JSON structure outlines the details of a single datasource, including its ID, name, description, category, type, modality, topics, example queries, pricing, response schema, update frequency, size, and coverage dates. It's used when querying for specific datasources. ```json { "success": true, "datasources": [ { "id": "valyu/valyu-arxiv", "name": "Arxiv", "description": "Over 1 million pre-print research papers...", "category": "research", "type": "text", "modality": ["text", "image"], "topics": ["physics", "computer science", "mathematics"], "example_queries": ["transformer attention mechanism"], "pricing": { "cpm": 0.50 }, "response_schema": {}, "update_frequency": "daily", "size": 1000000, "coverage": { "start_date": "1991-01-01", "end_date": null } } ], "total_count": 25, "categories": { "research": { "name": "Research & Academic", "count": 4 }, "markets": { "name": "Financial Markets", "count": 7 } } } ``` -------------------------------- ### Multi-Tool Search Example with Vercel AI SDK Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/vercel-ai-sdk.md Illustrates how to use multiple Valyu search tools (paperSearch, bioSearch, financeSearch) simultaneously within a single Vercel AI SDK prompt. This allows for comprehensive research across different domains. ```typescript import { generateText, stepCountIs } from "ai"; import { paperSearch, bioSearch, financeSearch } from "@valyu/ai-sdk"; import { openai } from "@ai-sdk/openai"; const { text } = await generateText({ model: openai('gpt-5'), prompt: 'Research the commercialization of CRISPR technology', tools: { papers: paperSearch({ maxNumResults: 3 }), medical: bioSearch({ maxNumResults: 3 }), finance: financeSearch({ maxNumResults: 3 }), }, stopWhen: stepCountIs(3), }); ``` -------------------------------- ### Choose the Right Search Tool for Financial Data (TypeScript) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/claude-agent-sdk.md Illustrates the best practice of selecting the appropriate search tool for specific data types. This example shows how to use the finance search tool to query for stock prices, specifying the tool identifier and the finance search server. ```typescript // Use finance search for financial data const financeResults = await query({ prompt: "What is Apple's stock price?", options: { allowedTools: ["mcp__valyu-finance-search__finance_search"], mcpServers: { "valyu-finance-search": valyuFinanceSearchServer }, }, }); ``` -------------------------------- ### Datasources Tool Example with Vercel AI SDK Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/vercel-ai-sdk.md Shows how to use the datasources tool to list available data sources and their metadata. This integrates with Vercel AI SDK for AI-driven data discovery. ```typescript import { generateText } from "ai"; import { datasources } from "@valyu/ai-sdk"; import { openai } from "@ai-sdk/openai"; const { text } = await generateText({ model: openai('gpt-5'), prompt: 'What data sources are available for financial research?', tools: { datasources: datasources(), }, }); ``` -------------------------------- ### ValyuToolSpec Initialization Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/llamaindex.md Parameters for initializing the ValyuToolSpec, including API key, search preferences, and content configuration. ```APIDOC ## ValyuToolSpec Initialization ### Description Parameters for initializing the ValyuToolSpec, including API key, search preferences, and content configuration. ### Method Initialization ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **`api_key`** (string) - Required - Valyu API key - **`verbose`** (boolean) - Optional - Enable verbose logging (default: False) - **`max_price`** (number) - Optional - Maximum cost in dollars for search operations - **`relevance_threshold`** (number) - Optional - Minimum relevance score 0.0-1.0 (default: 0.5) - **`fast_mode`** (boolean) - Optional - Enable fast mode for faster results (default: False) - **`included_sources`** (list of strings) - Optional - List of URLs/domains to include - **`excluded_sources`** (list of strings) - Optional - List of URLs/domains to exclude - **`response_length`** (string) - Optional - "short", "medium", "large", or "max" - **`country_code`** (string) - Optional - 2-letter ISO country code - **`contents_summary`** (boolean, string, or dict) - Optional - AI summary config - **`contents_extract_effort`** (string) - Optional - "normal", "high", or "auto" - **`contents_response_length`** (string) - Optional - Content length per URL ### Request Example ```json { "api_key": "YOUR_API_KEY", "verbose": true, "max_price": 5, "relevance_threshold": 0.7, "fast_mode": true, "included_sources": ["example.com"], "excluded_sources": ["spam.com"], "response_length": "medium", "country_code": "US", "contents_summary": true, "contents_extract_effort": "high", "contents_response_length": "medium" } ``` ### Response #### Success Response (200) Initialization does not typically return a response body, but confirms successful setup. #### Response Example None ``` -------------------------------- ### Basic OpenAI Responses API Integration with Valyu Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/openai.md Demonstrates the basic workflow of using the OpenAIProvider to integrate Valyu's search capabilities with OpenAI's Responses API. It involves initializing clients, getting tools, sending a user query, executing tool calls, and retrieving the final response. ```python from openai import OpenAI from valyu import OpenAIProvider from dotenv import load_dotenv load_dotenv() # Initialize clients openai_client = OpenAI() provider = OpenAIProvider() # Get Valyu tools tools = provider.get_tools() # Create a research request messages = [ { "role": "user", "content": "What are the latest developments in quantum computing? Write a summary of your findings." } ] # Step 1: Call OpenAI Responses API with tools response = openai_client.responses.create( model="gpt-5", input=messages, tools=tools, ) # Step 2: Execute tool calls tool_results = provider.execute_tool_calls(response) # Step 3: Get final response with search results if tool_results: updated_messages = provider.build_conversation(messages, response, tool_results) final_response = openai_client.responses.create( model="gpt-5", input=updated_messages, tools=tools, ) print(final_response.output_text) else: print(response.output_text) ``` -------------------------------- ### Quick Start: General Web Search with Vercel AI SDK Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/vercel-ai-sdk.md Demonstrates a basic integration of Valyu's webSearch tool with Vercel AI SDK's generateText function. It queries for data center projects and logs the text result. ```typescript import { generateText } from "ai"; import { webSearch } from "@valyu/ai-sdk"; import { openai } from "@ai-sdk/openai"; const { text } = await generateText({ model: openai('gpt-5'), prompt: 'Latest data center projects for AI inference workloads?', tools: { webSearch: webSearch(), }, }); console.log(text); ``` -------------------------------- ### Valyu Research Workflow Example Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/recipes.md Demonstrates a common research workflow using Valyu CLI commands. This workflow involves performing a quick search for sources, extracting key content from a URL, and then initiating a deep analysis task. ```bash # 1. Quick search to find sources scripts/valyu search paper "CRISPR therapeutic applications" 20 # 2. Extract key content scripts/valyu contents "https://arxiv.org/paper" --summary "Key findings" # 3. Deep analysis scripts/valyu deepresearch create "CRISPR therapeutic applications review" --model heavy --pdf ``` -------------------------------- ### Multi-Tool Agent with Claude Agent SDK Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/claude-agent-sdk.md Demonstrates how to configure a multi-tool agent using the Claude Agent SDK. This example allows the agent to utilize web search, finance search, and paper search tools simultaneously to research the impact of AI on financial markets. ```typescript import { query } from "@anthropic-ai/claude-agent-sdk"; import { valyuWebSearchServer, valyuFinanceSearchServer, valyuPaperSearchServer, } from "./tools/index.js"; async function multiToolAgent() { for await (const message of query({ prompt: "Research the impact of AI on financial markets, including recent news and academic papers", options: { model: "claude-sonnet-4-5", allowedTools: [ "mcp__valyu-web-search__web_search", "mcp__valyu-finance-search__finance_search", "mcp__valyu-paper-search__paper_search", ], mcpServers: { "valyu-web-search": valyuWebSearchServer, "valyu-finance-search": valyuFinanceSearchServer, "valyu-paper-search": valyuPaperSearchServer, }, }, })) { if (message.type === "assistant") { const textContent = message.content .filter((block) => block.type === "text") .map((block) => block.text) .join("\n"); console.log(textContent); } } } ``` -------------------------------- ### OpenAIProvider API Reference in Python Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/openai.md This Python code outlines the `OpenAIProvider` class, which facilitates interaction with OpenAI's API for research assistance. It includes methods for initializing the provider, retrieving tools, executing tool calls, and building conversation history. The `__init__` method allows for optional API key provision, defaulting to environment variable detection. ```python class OpenAIProvider: def __init__(self, valyu_api_key: Optional[str] = None): """Initialize provider. API key auto-detected from environment if not provided.""" def get_tools(self) -> List[Dict]: """Get list of tools formatted for OpenAI Responses API.""" def execute_tool_calls(self, response) -> List[Dict]: """Execute tool calls from OpenAI Responses API response.""" def build_conversation(self, input_messages, response, tool_results) -> List[Dict]: """Build updated message list with tool results.""" ``` -------------------------------- ### Install Valyu SDK for Python Source: https://github.com/valyuai/skills/blob/main/README.md Installs the Valyu Python SDK using pip. This SDK enables Python developers to integrate Valyu's data and research capabilities into their projects. ```bash pip install valyu ``` -------------------------------- ### OpenAI Integration with Valyu Provider (Python) Source: https://context7.com/valyuai/skills/llms.txt This Python snippet illustrates the initial setup for integrating Valyu with OpenAI's Responses API. It shows how to initialize the OpenAI client and the Valyu OpenAIProvider, and retrieve the available tools for use with OpenAI agents. ```python from openai import OpenAI from valyu import OpenAIProvider # Initialize openai_client = OpenAI() provider = OpenAIProvider() tools = provider.get_tools() ``` -------------------------------- ### Install Valyu SDK for JavaScript/TypeScript Source: https://github.com/valyuai/skills/blob/main/README.md Installs the Valyu JavaScript SDK using npm. This SDK allows developers to interact with the Valyu API directly within their Node.js or browser applications. ```bash npm install valyu-js ``` -------------------------------- ### AI-Powered Question Answering with Custom Instructions Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/SKILL.md Allows for customized AI responses by providing specific system instructions. This example requests a balanced comparison of React and Vue for enterprise applications, formatted as a comparison table. ```typescript const response = await valyu.answer({ query: "Compare React and Vue for enterprise applications", systemInstructions: "Provide a balanced comparison with pros and cons. Format as a comparison table." }); ``` -------------------------------- ### Cost Optimization with Bio Search Server Configurations (TypeScript) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/claude-agent-sdk.md Demonstrates cost optimization by creating different configurations for the bio search server. 'quickSearch' is configured with fewer results and a lower price limit for faster, cheaper searches, while 'deepSearch' allows for more results and a higher price limit for more comprehensive searches. ```typescript const quickSearch = createBioSearchServer({ maxNumResults: 3, maxPrice: 15.0, relevanceThreshold: 0.6, }); const deepSearch = createBioSearchServer({ maxNumResults: 20, maxPrice: 50.0, relevanceThreshold: 0.5, }); ``` -------------------------------- ### Valyu CLI Tool Usage Source: https://context7.com/valyuai/skills/llms.txt This section details the commands available for the Valyu Command Line Interface (CLI). It covers setting up API keys, performing various types of searches (web, paper, finance, news, bio), extracting content from URLs, getting AI-generated answers, and managing deep research tasks. ```bash # Setup API key scripts/valyu setup # Search commands scripts/valyu search web "AI news" 10 scripts/valyu search paper "CRISPR gene editing" 20 scripts/valyu search finance "Tesla earnings Q4 2024" 10 scripts/valyu search news "Federal Reserve interest rate" 20 scripts/valyu search bio "clinical trials diabetes" 15 # Content extraction scripts/valyu contents "https://example.com/article" scripts/valyu contents "https://arxiv.org/abs/2401.12345" --summary "Key findings in 3 points" scripts/valyu contents "https://store.example.com" --structured '{"type":"object","properties":{"title":{"type":"string"}}}' # AI answers scripts/valyu answer "What are the latest developments in quantum computing?" scripts/valyu answer "Current Bitcoin price" --fast # Deep research scripts/valyu deepresearch create "AI market trends 2024" --model standard scripts/valyu deepresearch create "EV battery technology" --model heavy --pdf scripts/valyu deepresearch status ``` -------------------------------- ### Install Valyu AgentCore for Strands or AWS AgentCore Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/aws-agentcore.md Installs the Valyu AgentCore library. Use the `[strands]` extra for local development with Strands Agents, or `[agentcore]` for AWS AgentCore Gateway/Runtime deployments. ```bash # For local development with Strands Agents pip install "valyu-agentcore[strands]" # For AWS AgentCore Gateway/Runtime deployment pip install "valyu-agentcore[agentcore]" ``` -------------------------------- ### Get AI Answers with Citations using Answer API (TypeScript) Source: https://context7.com/valyuai/skills/llms.txt This snippet demonstrates using the Valyu Answer API to get AI-powered answers grounded in real-time search results, including citations. It supports custom instructions for tailored responses and can be configured for faster responses. ```typescript import { Valyu } from "valyu-js"; const valyu = new Valyu(process.env.VALYU_API_KEY); // Basic answer const response = await valyu.answer({ query: "What are the latest developments in quantum computing?" }); console.log(response.contents); console.log(`Sources: ${response.searchResults.length}`); console.log(`Cost: $${response.cost.totalDeductionDollars}`); // With custom instructions const customAnswer = await valyu.answer({ query: "Compare React and Vue for enterprise applications", systemInstructions: "Provide a balanced comparison with pros and cons. Format as a comparison table.", fastMode: true // Lower latency }); // Structured output const structured = await valyu.answer({ query: "Apple Q4 2024 financial highlights", structuredOutput: { type: "object", properties: { revenue: { type: "string" }, growthRate: { type: "string" }, keyHighlights: { type: "array", items: { type: "string" } } } } }); ``` -------------------------------- ### List Categories Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md Retrieves a list of all available categories for datasources, including the count of datasets within each category. ```APIDOC ## GET /v1/datasources/categories ### Description Returns all available categories with dataset counts. This endpoint helps users understand the breadth of data available across different domains. ### Method GET ### Endpoint /v1/datasources/categories ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **categories** (array) - An array of category objects, each containing an id, name, description, and dataset_count. #### Response Example ```json { "success": true, "categories": [ { "id": "research", "name": "Research & Academic", "description": "Academic papers and research publications", "dataset_count": 4 }, { "id": "markets", "name": "Financial Markets", "description": "Real-time and historical market data", "dataset_count": 7 }, { "id": "healthcare", "name": "Healthcare & Medical", "description": "Clinical trials, drug information, and health data", "dataset_count": 4 } ] } ``` ``` -------------------------------- ### Datasources API - List Datasources Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md Retrieves a list of all available data sources with their metadata, pricing, and schemas. ```APIDOC ## GET /v1/datasources ### Description Retrieves a list of all available data sources with their metadata, pricing, and schemas. Useful for AI agents to understand available data. ### Method GET ### Endpoint /v1/datasources ### Parameters #### Query Parameters - **category** (string) - Optional - Filter the results by data source category. Valid categories: `research`, `healthcare`, `patents`, `markets`, `company`, `economic`, `predictions`, `transportation`, `legal`, `politics`. ### Response #### Success Response (200) Returns a JSON object containing a list of available datasources. The exact structure of each datasource object is not detailed here but would typically include: - **id** (string) - Unique identifier for the datasource. - **name** (string) - Human-readable name of the datasource. - **description** (string) - A brief description of the datasource. - **category** (string) - The category the datasource belongs to. - **pricing** (object) - Information about the cost associated with using the datasource. - **schema** (object) - The schema definition for data from this source. #### Response Example ```json { "datasources": [ { "id": "company_financials", "name": "Company Financial Statements", "description": "Quarterly and annual financial reports for public companies.", "category": "company", "pricing": {"cost_per_query": 0.01}, "schema": {"type": "object", "properties": {"revenue": {"type": "number"}, "net_income": {"type": "number"}}} }, { "id": "market_indices", "name": "Global Market Indices", "description": "Historical and current data for major stock market indices.", "category": "markets", "pricing": {"cost_per_query": 0.005}, "schema": {"type": "object", "properties": {"index_name": {"type": "string"}, "value": {"type": "number"}}} } ] } ``` ``` -------------------------------- ### Deploy Agent for Local Development (Python) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/aws-agentcore.md A minimal Python example for setting up an agent for local development and testing purposes. It configures an agent with the `webSearch` tool and a specified Bedrock model. ```python from valyu_agentcore import webSearch from strands import Agent from strands.models import BedrockModel agent = Agent( model=BedrockModel(model_id="us.anthropic.claude-sonnet-4-20250514-v1:0"), tools=[webSearch()], ) ``` -------------------------------- ### Answer API Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/api-guide.md Provides AI-powered answers grounded in real-time search results, complete with citations for verification. ```APIDOC ## POST /v1/answer ### Description AI-powered answers grounded in real-time search results with citations. ### Method POST ### Endpoint /v1/answer ### Parameters #### Query Parameters - **query** (string) - Required - The question to be answered. - **search_type** (enum) - Optional - Default: "all" - Specifies the type of sources to search. Options: "all", "web", "proprietary", "news". - **max_num_results** (int) - Optional - Default: 5 - Maximum number of search results to consider for the answer. - **response_length** (enum/int) - Optional - Default: "medium" - Desired length of the answer. Options: "short" (25k), "medium" (50k), "large" (100k), "max", or custom int. - **country_code** (string) - Optional - 2-letter ISO code for geographic bias in search. ### Request Example ```json { "query": "What are the main causes of climate change?", "max_num_results": 10, "response_length": "large" } ``` ### Response #### Success Response (200) - **success** (bool) - Indicates if the request was successful. - **tx_id** (string) - Transaction ID for the request. - **answer** (string) - The AI-generated answer to the query. - **citations** (array) - A list of sources used to generate the answer, including titles and URLs. - **total_deduction_dollars** (float) - The total cost deducted for this request. #### Response Example ```json { "success": true, "tx_id": "tx_def456", "answer": "The main causes of climate change include the burning of fossil fuels, deforestation, and industrial processes, leading to increased greenhouse gas emissions.", "citations": [ { "title": "IPCC Report on Climate Change Causes", "url": "https://www.ipcc.ch/report/" }, { "title": "NASA: Global Climate Change", "url": "https://climate.nasa.gov/causes/" } ], "total_deduction_dollars": 0.015 } ``` ``` -------------------------------- ### Configure Valyu Finance Search Tool with Custom Parameters (Python) Source: https://github.com/valyuai/skills/blob/main/valyu-search/valyu-best-practices/references/integrations/aws-agentcore.md Demonstrates detailed configuration of the `financeSearch` tool. Allows customization of API key, search type, result limits, price thresholds, source inclusion/exclusion, and categorization for targeted financial analysis. ```python from valyu_agentcore import financeSearch tool = financeSearch( api_key="val_xxx", search_type="all", max_num_results=10, max_price=0.50, relevance_threshold=0.7, excluded_sources=["reddit.com"], included_sources=["reuters.com"], category="quarterly earnings", ) ```