import requestsfrom langchain.agents import create_agentfrom langchain.messages import HumanMessagefrom langchain.tools import toolfrom markdownify import markdownifyALLOWED_DOMAINS = ["https://langchain-ai.github.io/"]LLMS_TXT = 'https://langchain-ai.github.io/langgraph/llms.txt'@tooldef fetch_documentation(url: str) -> str: """获取并转换 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)# 我们将获取 llms.txt 的内容,因此可以# 提前完成,无需 LLM 请求。llms_txt_content = requests.get(LLMS_TXT).text# 智能体的系统提示词system_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)