Janneyffr commited on
Commit
4acd4c5
·
verified ·
1 Parent(s): d930a67

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +86 -0
  2. retriever.py +19 -0
  3. tools.py +68 -0
app.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import TypedDict, Annotated
2
+ from langgraph.graph.message import add_messages
3
+ from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
4
+ from langgraph.prebuilt import ToolNode
5
+ from langgraph.graph import START, StateGraph
6
+ from langgraph.prebuilt import tools_condition
7
+ from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
8
+
9
+ from tools import search_tool, weather_info_tool, hub_stats_tool, guest_info_tool
10
+ from retriever import docs
11
+
12
+ from langchain_ollama import ChatOllama
13
+
14
+
15
+ # 生成聊天界面,包括工具
16
+ llm = ChatOllama(model="gpt-oss:20b", request_timeout=120.0)
17
+
18
+ tools = [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool]
19
+
20
+ chat_with_tools = llm.bind_tools(tools)
21
+ # 生成 AgentState 和 Agent 图
22
+ class AgentState(TypedDict):
23
+ messages: Annotated[list[AnyMessage], add_messages]
24
+
25
+ def assistant(state: AgentState):
26
+ return {
27
+ "messages": [chat_with_tools.invoke(state["messages"])],
28
+ }
29
+
30
+ ## 构建流程图
31
+ builder = StateGraph(AgentState)
32
+
33
+ # 定义节点:执行具体工作
34
+ builder.add_node("assistant", assistant)
35
+ builder.add_node("tools", ToolNode(tools))
36
+
37
+ # 定义边:控制流程走向
38
+ builder.add_edge(START, "assistant")
39
+ builder.add_conditional_edges(
40
+ "assistant",
41
+ # 如果最新消息需要工具调用,则路由到 tools 节点
42
+ # 否则直接响应
43
+ tools_condition,
44
+ )
45
+ builder.add_edge("tools", "assistant")
46
+ alfred = builder.compile()
47
+
48
+ #示例1
49
+ # response = alfred.invoke({"messages": "Tell me about 'Lady Ada Lovelace' and translate output to chinese."})
50
+
51
+ # print("🎩 Alfred's Response:")
52
+ # print(response['messages'][-1].content)
53
+
54
+ #示例2
55
+ # response = alfred.invoke({"messages": "What's the weather like in Tokyo tonight? Will it be suitable for our fireworks display?and translate output to chinese."})
56
+
57
+ # print("🎩 Alfred's Response:")
58
+ # print(response['messages'][-1].content)
59
+
60
+ #示例 3:给 AI 研究者留下深刻印象
61
+ # response = alfred.invoke({"messages": "One of our guests is from Qwen. What can you tell me about their most popular model?请用中文回答"})
62
+
63
+ # print("🎩 Alfred's Response:")
64
+ # print(response['messages'][-1].content)
65
+
66
+ #示例 4:组合多工具应用
67
+ # response = alfred.invoke({"messages":"我需要与“尼古拉·特斯拉博士”讨论最近在无线能源方面的进展。你能帮我为这次对话做准备吗?"})
68
+
69
+ # print("🎩 Alfred's Response:")
70
+ # print(response['messages'][-1].content)
71
+
72
+ #高级功能:对话记忆
73
+
74
+ # 首次交互
75
+ response = alfred.invoke({"messages": [HumanMessage(content="Tell me about 'Lady Ada Lovelace'. What's her background and how is she related to me?请用中文回答")]})
76
+
77
+
78
+ print("🎩 Alfred's Response:")
79
+ print(response['messages'][-1].content)
80
+ print("以下是第二次对话内容")
81
+
82
+ # 二次交互(引用首次内容)
83
+ response = alfred.invoke({"messages": response["messages"] + [HumanMessage(content="What projects is she currently working on?请用中文回答")]})
84
+
85
+ print("🎩 Alfred's Response:")
86
+ print(response['messages'][-1].content)
retriever.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datasets
2
+ from langchain_core.documents import Document
3
+
4
+ # 加载数据集
5
+ guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train")
6
+
7
+ # 转换为 Document 对象
8
+ docs = [
9
+ Document(
10
+ page_content="\n".join([
11
+ f"Name: {guest['name']}",
12
+ f"Relation: {guest['relation']}",
13
+ f"Description: {guest['description']}",
14
+ f"Email: {guest['email']}"
15
+ ]),
16
+ metadata={"name": guest["name"]}
17
+ )
18
+ for guest in guest_dataset
19
+ ]
tools.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.retrievers import BM25Retriever
2
+ from langchain.tools import Tool
3
+ from langchain_community.tools import DuckDuckGoSearchRun
4
+ from huggingface_hub import list_models
5
+ import random
6
+ from retriever import docs
7
+ import requests
8
+
9
+ #知识库检索工具
10
+ bm25_retriever = BM25Retriever.from_documents(docs)
11
+
12
+ def extract_text(query: str) -> str:
13
+ """Retrieves detailed information about gala guests based on their name or relation."""
14
+ results = bm25_retriever.invoke(query)
15
+ if results:
16
+ return "\n\n".join([doc.page_content for doc in results[:3]])
17
+ else:
18
+ return "No matching guest information found."
19
+
20
+ guest_info_tool = Tool(
21
+ name="guest_info_retriever",
22
+ func=extract_text,
23
+ description="Retrieves detailed information about gala guests based on their name or relation."
24
+ )
25
+
26
+
27
+ #网络搜索工具
28
+ search_tool = DuckDuckGoSearchRun()
29
+
30
+ #天气查询工具
31
+ def get_weather_info(location: str) -> str:
32
+ """Fetches weather information from wttr.in for a given location."""
33
+ url = f"https://wttr.in/{location}?format=3" # 简洁格式:City: +天气 +温度
34
+ try:
35
+ response = requests.get(url, timeout=10)
36
+ return response.text
37
+ except Exception as e:
38
+ return f"Error fetching weather: {str(e)}"
39
+
40
+ # 初始化工具
41
+ weather_info_tool = Tool(
42
+ name="get_weather_info",
43
+ func=get_weather_info,
44
+ description="Fetches dummy weather information for a given location."
45
+ )
46
+
47
+ #为有影响力的 AI 开发者创建 Hub 统计工具
48
+
49
+ def get_hub_stats(author: str) -> str:
50
+ """Fetches the most downloaded model from a specific author on the Hugging Face Hub."""
51
+ try:
52
+ # 列出指定作者的模型,按下载次数排序
53
+ models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
54
+
55
+ if models:
56
+ model = models[0]
57
+ return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
58
+ else:
59
+ return f"No models found for author {author}."
60
+ except Exception as e:
61
+ return f"Error fetching models for {author}: {str(e)}"
62
+
63
+ # 初始化工具
64
+ hub_stats_tool = Tool(
65
+ name="get_hub_stats",
66
+ func=get_hub_stats,
67
+ description="Fetches the most downloaded model from a specific author on the Hugging Face Hub."
68
+ )