代理实现 RAG 行为唯一需要的是访问一个或多个可以获取外部知识的工具——例如文档加载器、Web API 或数据库查询。
复制
向 AI 提问
import requestsfrom langchain.tools import toolfrom langchain.chat_models import init_chat_modelfrom langchain.agents import create_agent@tooldef fetch_url(url: str) -> str: """Fetch text content from a URL""" response = requests.get(url, timeout=10.0) response.raise_for_status() return response.textsystem_prompt = """\Use fetch_url when you need to fetch information from a web-page; quote relevant snippets."""agent = create_agent( model="claude-sonnet-4-5-20250929", tools=[fetch_url], # A tool for retrieval system_prompt=system_prompt,)
import requestsfrom langchain.agents import create_agentfrom langchain.messages import HumanMessagefrom langchain.tools import toolfrom markdownify import markdownifyALLOWED_DOMAINS = ["https://github.langchain.ac.cn/"]LLMS_TXT = 'https://github.langchain.ac.cn/langgraph/llms.txt'@tooldef fetch_documentation(url: str) -> str: """Fetch and convert documentation from a URL""" if not any(url.startswith(domain) for domain in ALLOWED_DOMAINS): return ( "Error: URL not allowed. " f"Must start with one of: {', '.join(ALLOWED_DOMAINS)}" ) response = requests.get(url, timeout=10.0) response.raise_for_status() return markdownify(response.text)# We will fetch the content of llms.txt, so this can# be done ahead of time without requiring an LLM request.llms_txt_content = requests.get(LLMS_TXT).text# System prompt for the agentsystem_prompt = f"""You are an expert Python developer and technical assistant.Your primary role is to help users with questions about LangGraph and related tools.Instructions:1. If a user asks a question you're unsure about — or one that likely involves API usage, behavior, or configuration — you MUST use the `fetch_documentation` tool to consult the relevant docs.2. When citing documentation, summarize clearly and include relevant context from the content.3. Do not use any URLs outside of the allowed domain.4. If a documentation fetch fails, tell the user and proceed with your best expert understanding.You can access official documentation from the following approved sources:{llms_txt_content}You MUST consult the documentation to get up to date documentationbefore answering a user's question about LangGraph.Your answers should be clear, concise, and technically accurate."""tools = [fetch_documentation]model = init_chat_model("claude-sonnet-4-0", max_tokens=32_000)agent = create_agent( model=model, tools=tools, system_prompt=system_prompt, name="Agentic RAG",)response = agent.invoke({ 'messages': [ HumanMessage(content=( "Write a short example of a langgraph agent using the " "prebuilt create react agent. the agent should be able " "to look up stock pricing information." )) ]})print(response['messages'][-1].content)