File size: 4,723 Bytes
d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 664b67c d9c23d1 664b67c fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 b7d2d3d d9c23d1 fc07371 d9c23d1 fc07371 3681af9 d9c23d1 fc07371 d9c23d1 664b67c d9c23d1 fc07371 d9c23d1 3681af9 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 fc07371 d9c23d1 b7d2d3d fc07371 d9c23d1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
import os
from dotenv import load_dotenv
from langgraph.graph import START, StateGraph, MessagesState
from langgraph.prebuilt import tools_condition, ToolNode
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_groq import ChatGroq
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_community.document_loaders import WikipediaLoader, ArxivLoader
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.tools import tool
from langchain_groq import ChatGroq
load_dotenv()
# ------------------- TOOL DEFINITIONS -------------------
@tool
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
@tool
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
@tool
def subtract(a: int, b: int) -> int:
"""Subtract two numbers."""
return a - b
@tool
def divide(a: int, b: int) -> float:
"""Divide two numbers."""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
@tool
def modulus(a: int, b: int) -> int:
"""Get the modulus of two numbers."""
return a % b
@tool
def wiki_search(query: str) -> str:
"""Search Wikipedia for a query (max 2 results)."""
docs = WikipediaLoader(query=query, load_max_docs=2).load()
return "\n\n".join([doc.page_content for doc in docs])
@tool
def web_search(query: str) -> str:
"""Search the web using Tavily (max 3 results)."""
results = TavilySearchResults(max_results=3).invoke(query)
texts = []
for doc in results:
if isinstance(doc, dict):
texts.append(doc.get("content", "") or doc.get("text", ""))
return "\n\n".join(texts)
@tool
def arvix_search(query: str) -> str:
"""Search Arxiv for academic papers (max 3)."""
docs = ArxivLoader(query=query, load_max_docs=3).load()
return "\n\n".join([doc.page_content[:1000] for doc in docs])
tools = [multiply, add, subtract, divide, modulus, wiki_search, web_search, arvix_search]
# ------------------- SYSTEM PROMPT -------------------
system_prompt_path = "system_prompt.txt"
if os.path.exists(system_prompt_path):
with open(system_prompt_path, "r", encoding="utf-8") as f:
system_prompt = f.read()
else:
system_prompt = (
"You are an intelligent AI agent who can solve math, science, factual, and research-based problems. "
"You can use tools like Wikipedia, Web search, or Arxiv when needed. Always give precise and helpful answers."
)
sys_msg = SystemMessage(content=system_prompt)
# ------------------- GRAPH CONSTRUCTION -------------------
from langchain_openai import ChatOpenAI # ✅ 新增导入
def build_graph(provider: str = "groq"):
"""Build the LangGraph with tool-use."""
if provider == "google":
llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash", temperature=0)
elif provider == "groq":
groq_key = os.getenv("GROQ_API_KEY")
if not groq_key:
raise ValueError("GROQ_API_KEY is not set.")
llm = ChatGroq(model="qwen-qwq-32b", temperature=0, api_key=groq_key)
elif provider == "huggingface":
llm = ChatHuggingFace(
llm=HuggingFaceEndpoint(
url="https://api-inference.huggingface.co/models/Meta-DeepLearning/llama-2-7b-chat-hf",
temperature=0
)
)
elif provider == "openai":
openai_key = os.getenv("OPENAI_API_KEY")
if not openai_key:
raise ValueError("OPENAI_API_KEY is not set.")
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0, api_key=openai_key) # ✅ OpenAI GPT
else:
raise ValueError("Invalid provider")
llm_with_tools = llm.bind_tools(tools)
def assistant(state: MessagesState):
return {"messages": [sys_msg] + [llm_with_tools.invoke(state["messages"])]}
# Build the graph with assistant and tools
builder = StateGraph(MessagesState)
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "assistant")
builder.add_conditional_edges("assistant", tools_condition)
builder.add_edge("tools", "assistant")
return builder.compile()
# ------------------- LOCAL TEST -------------------
if __name__ == "__main__":
question = "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect?"
graph = build_graph(provider="openai")
messages = graph.invoke({"messages": [HumanMessage(content=question)]})
print("=== AI Agent Response ===")
for m in messages["messages"]:
m.pretty_print()
|