NitroSnow commited on
Commit
32ebe58
·
verified ·
1 Parent(s): 81917a3

Upload 3 files

Browse files
Files changed (3) hide show
  1. Gala_Agent.py +58 -0
  2. retriever.py +41 -0
  3. tools.py +48 -0
Gala_Agent.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LangGraph RAG Agent 整合所有必要组件
3
+ """
4
+ from typing import TypedDict, Annotated
5
+ from langgraph.graph.message import add_messages
6
+ from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
7
+ from langgraph.prebuilt import ToolNode
8
+ from langgraph.graph import START, StateGraph
9
+ from langgraph.prebuilt import tools_condition
10
+ from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
11
+ from langchain_openai import ChatOpenAI
12
+ from tools import DuckDuckGoSearchRun, weather_info_tool, hub_stats_tool
13
+ from retriever import guest_info_tool
14
+
15
+ search_tool = DuckDuckGoSearchRun()
16
+
17
+ DOUBAO_API_KEY = "cc556f72-0b09-4899-b9c3-ca2d2b4db8a5"
18
+ DOUBAO_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3"
19
+ llm = ChatOpenAI(
20
+ model="doubao-seed-1-8-251228",
21
+ openai_api_key=DOUBAO_API_KEY,
22
+ openai_api_base=DOUBAO_BASE_URL,
23
+ )
24
+ tools = [
25
+ guest_info_tool, search_tool, weather_info_tool, hub_stats_tool,
26
+ ]
27
+ chat_with_tools = llm.bind_tools(tools)
28
+
29
+ class AgentState(TypedDict):
30
+ messages: Annotated[list[AnyMessage], add_messages]
31
+
32
+ def assistant(state: AgentState):
33
+ return {
34
+ "messages": [chat_with_tools.invoke(state["messages"])]
35
+ }
36
+
37
+ builder = StateGraph(AgentState)
38
+
39
+ builder.add_node("assistant", assistant)
40
+ builder.add_node("tools", ToolNode(tools))
41
+
42
+ builder.add_edge(START, "assistant")
43
+ builder.add_conditional_edges(
44
+ "assistant",
45
+ tools_condition
46
+ )
47
+
48
+ builder.add_edge("tools", "assistant")
49
+ alfred = builder.compile()
50
+
51
+ # 示例1:获取嘉宾信息
52
+ # response = alfred.invoke({"messages": "告诉我关于 Ada Lovelace的信息"})
53
+
54
+
55
+ # 组合多工具应用
56
+ response = alfred.invoke({"messages":"I need to speak with 'Dr. Nikola Tesla' about recent advancements in wireless energy. Can you help me prepare for this conversation?"})
57
+ print("🎩 Alfred's Response:")
58
+ print(response['messages'][-1].content)
retriever.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.retrievers import BM25Retriever
2
+ from langchain_core.tools import Tool
3
+ from importlib.metadata import metadata
4
+
5
+ # 加载数据集
6
+ import datasets
7
+ from langchain_core.documents import Document
8
+
9
+ guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train")
10
+
11
+ # 转换为 Document 对象
12
+ docs = [
13
+ Document(
14
+ page_content="\n".join([
15
+ f"Name: {guest['name']}",
16
+ f"Relation: {guest['relation']}",
17
+ f"Description: {guest['description']}",
18
+ f"Email: {guest['email']}",
19
+ ]),
20
+ metadata={"name": guest["name"]}
21
+ )
22
+ for guest in guest_dataset
23
+ ]
24
+
25
+ bm25_retriever = BM25Retriever.from_documents(docs)
26
+
27
+ def extract_text(query:str) -> str:
28
+ """
29
+ Retrieves detailed information about gala guests based on their name or relation
30
+ """
31
+ results = bm25_retriever.invoke(query)
32
+ if results:
33
+ return "\n\n".join([doc.page_content for doc in results[:3]])
34
+ else:
35
+ return "No matching guest information found."
36
+
37
+ guest_info_tool = Tool(
38
+ name="guest_info_retriever",
39
+ func=extract_text,
40
+ description="Retrieves detailed information about gala guests based on their name or relation."
41
+ )
tools.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.tools import Tool
2
+ from huggingface_hub import list_models
3
+
4
+ def get_hub_stats(author:str) -> str:
5
+ """Fetches the most downloaded model from a specific author on the Hugging Face Hub"""
6
+ try:
7
+ models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
8
+
9
+ if models:
10
+ model = models[0]
11
+ return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
12
+ else:
13
+ return f"No models found for author {author}."
14
+ except Exception as e:
15
+ return f"Error fetching models for {author}: {str(e)}"
16
+
17
+ # 初始化工具
18
+ hub_stats_tool = Tool(
19
+ name="get_hub_stats",
20
+ func=get_hub_stats,
21
+ description="Fetches the most downloaded model from a specific author on the Hugging Face Hub."
22
+ )
23
+
24
+
25
+
26
+ from langchain_core.tools import Tool
27
+ import random
28
+
29
+ def get_weather_info(location: str) -> str:
30
+ """Fetches dummy weather information for a give location"""
31
+ # mock data
32
+ weather_conditions = [
33
+ {"condition": "Rainy", "temp_c": 15},
34
+ {"condition": "Clear", "temp_c": 25},
35
+ {"condition": "Windy", "temp_c": 20}
36
+ ]
37
+ data = random.choice(weather_conditions)
38
+ return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C"
39
+
40
+ weather_info_tool = Tool(
41
+ name="get_weather_info",
42
+ func=get_weather_info,
43
+ description="Fetches dummy weather information for a give location"
44
+ )
45
+
46
+ from langchain_community.tools import DuckDuckGoSearchRun
47
+
48
+ search_tool = DuckDuckGoSearchRun()