| | from typing import TypedDict, Annotated
|
| | from langgraph.graph.message import add_messages
|
| | from langchain_core.messages import AnyMessage, HumanMessage, AIMessage
|
| | from langgraph.prebuilt import ToolNode
|
| | from langgraph.graph import START, StateGraph
|
| | from langgraph.prebuilt import tools_condition
|
| | from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| |
|
| | from tools import search_tool, weather_info_tool, hub_stats_tool, guest_info_tool
|
| | from retriever import docs
|
| |
|
| | from langchain_ollama import ChatOllama
|
| | import os
|
| | HF_TOKEN = os.environ.get("HF_TOKEN")
|
| | if HF_TOKEN is None:
|
| | raise RuntimeError("⚠️ 没有找到 HF_TOKEN,请先在 Spaces 的 Variables and secrets 添加。")
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | tools = [guest_info_tool, search_tool, weather_info_tool, hub_stats_tool]
|
| |
|
| |
|
| | llm = HuggingFaceEndpoint(
|
| | repo_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| | huggingfacehub_api_token=HF_TOKEN,
|
| | )
|
| |
|
| | chat = ChatHuggingFace(llm=llm, verbose=True)
|
| | tools = [guest_info_tool]
|
| | chat_with_tools = chat.bind_tools(tools)
|
| |
|
| |
|
| | class AgentState(TypedDict):
|
| | messages: Annotated[list[AnyMessage], add_messages]
|
| |
|
| | def assistant(state: AgentState):
|
| | return {
|
| | "messages": [chat_with_tools.invoke(state["messages"])],
|
| | }
|
| |
|
| |
|
| | builder = StateGraph(AgentState)
|
| |
|
| |
|
| | 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")
|
| | alfred = builder.compile()
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| |
|
| | response = alfred.invoke({"messages": [HumanMessage(content="Tell me about 'Lady Ada Lovelace'. What's her background and how is she related to me?请用中文回答")]})
|
| |
|
| |
|
| | print("🎩 Alfred's Response:")
|
| | print(response['messages'][-1].content)
|
| | print("以下是第二次对话内容")
|
| |
|
| |
|
| | response = alfred.invoke({"messages": response["messages"] + [HumanMessage(content="What projects is she currently working on?请用中文回答")]})
|
| |
|
| | print("🎩 Alfred's Response:")
|
| | print(response['messages'][-1].content) |