Update app.py
Browse files
app.py
CHANGED
|
@@ -1,23 +1,19 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import json
|
| 3 |
from dataclasses import dataclass, field, asdict
|
| 4 |
-
from typing import List, Dict, Any, Tuple, TypedDict
|
| 5 |
|
| 6 |
# --- 1. 数据结构与核心逻辑 (无变化) ---
|
| 7 |
@dataclass
|
| 8 |
-
class Entity:
|
| 9 |
-
name: str; entityType: str; observations: List[str] = field(default_factory=list)
|
| 10 |
@dataclass
|
| 11 |
-
class Relation:
|
| 12 |
-
from_entity: str; to_entity: str; relationType: str
|
| 13 |
@dataclass
|
| 14 |
-
class KnowledgeGraph:
|
| 15 |
-
entities: Dict[str, Entity] = field(default_factory=dict); relations: List[Relation] = field(default_factory=list)
|
| 16 |
|
| 17 |
class KnowledgeGraphManager:
|
| 18 |
# ... (Manager 的所有内部方法保持不变) ...
|
| 19 |
-
def __init__(self):
|
| 20 |
-
self.graph = KnowledgeGraph(); print("Initialized a new, empty in-memory knowledge graph.")
|
| 21 |
def create_entities(self, entities_data: List[Dict]) -> List[Entity]:
|
| 22 |
new_entities = []; [ (new_entity := Entity(**e_data), self.graph.entities.update({e_data['name']: new_entity}), new_entities.append(new_entity)) for e_data in entities_data if e_data['name'] not in self.graph.entities]; return new_entities
|
| 23 |
def create_relations(self, relations_data: List[Dict]) -> List[Relation]:
|
|
@@ -51,34 +47,58 @@ class DeleteRelationsPayload(TypedDict): relations: List[Dict]
|
|
| 51 |
class SearchNodesPayload(TypedDict): query: str
|
| 52 |
class OpenNodesPayload(TypedDict): names: List[str]
|
| 53 |
|
| 54 |
-
# --- 3. API 工具函数定义 (使用
|
| 55 |
-
def create_entities(payload:
|
| 56 |
-
"""在知识图谱中创建多个新实体。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
new_entities = kg_manager.create_entities(payload['entities'])
|
| 58 |
return json.dumps([asdict(e) for e in new_entities], indent=2)
|
| 59 |
|
| 60 |
-
def create_relations(payload:
|
| 61 |
-
"""在知识图谱中的实体之间创建多个新关系。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
new_relations = kg_manager.create_relations(payload['relations'])
|
| 63 |
return json.dumps([{"from": r.from_entity, "to": r.to_entity, "relationType": r.relationType} for r in new_relations], indent=2)
|
| 64 |
|
| 65 |
-
def add_observations(payload:
|
| 66 |
-
"""向知识图谱中已存在的实体添加新的观察记录。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
results = kg_manager.add_observations(payload['observations'])
|
| 68 |
return json.dumps(results, indent=2)
|
| 69 |
|
| 70 |
-
def delete_entities(payload:
|
| 71 |
-
"""从知识图谱中删除多个实体及其相关联的关系。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
kg_manager.delete_entities(payload['entityNames'])
|
| 73 |
return "Entities and their relations deleted successfully."
|
| 74 |
|
| 75 |
-
def delete_observations(payload:
|
| 76 |
-
"""从知识图谱中的实体删除特定的观察
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
kg_manager.delete_observations(payload['deletions'])
|
| 78 |
return "Observations deleted successfully."
|
| 79 |
|
| 80 |
-
def delete_relations(payload:
|
| 81 |
-
"""从知识图谱中删除多个关系。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
kg_manager.delete_relations(payload['relations'])
|
| 83 |
return "Relations deleted successfully."
|
| 84 |
|
|
@@ -86,12 +106,20 @@ def read_graph() -> Dict:
|
|
| 86 |
"""读取并返回整个知识图谱。此函数不需要参数。"""
|
| 87 |
return kg_manager.read_graph()
|
| 88 |
|
| 89 |
-
def search_nodes(payload:
|
| 90 |
-
"""根据查询词在知识图谱中搜索节点。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
return kg_manager.search_nodes(payload['query'])
|
| 92 |
|
| 93 |
-
def open_nodes(payload:
|
| 94 |
-
"""通过名称打开知识图谱中的特定节点。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
return kg_manager.open_nodes(payload['names'])
|
| 96 |
|
| 97 |
# --- 4. Gradio Headless 应用构建与 API 注册 (无变化) ---
|
|
@@ -110,4 +138,23 @@ with gr.Blocks() as app:
|
|
| 110 |
dummy_btn.click(fn=open_nodes, inputs=json_input, outputs=generic_output, api_name="open_nodes")
|
| 111 |
|
| 112 |
if __name__ == "__main__":
|
| 113 |
-
app.launch(mcp_server=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import json
|
| 3 |
from dataclasses import dataclass, field, asdict
|
| 4 |
+
from typing import List, Dict, Any, Tuple, TypedDict
|
| 5 |
|
| 6 |
# --- 1. 数据结构与核心逻辑 (无变化) ---
|
| 7 |
@dataclass
|
| 8 |
+
class Entity: name: str; entityType: str; observations: List[str] = field(default_factory=list)
|
|
|
|
| 9 |
@dataclass
|
| 10 |
+
class Relation: from_entity: str; to_entity: str; relationType: str
|
|
|
|
| 11 |
@dataclass
|
| 12 |
+
class KnowledgeGraph: entities: Dict[str, Entity] = field(default_factory=dict); relations: List[Relation] = field(default_factory=list)
|
|
|
|
| 13 |
|
| 14 |
class KnowledgeGraphManager:
|
| 15 |
# ... (Manager 的所有内部方法保持不变) ...
|
| 16 |
+
def __init__(self): self.graph = KnowledgeGraph(); print("Initialized a new, empty in-memory knowledge graph.")
|
|
|
|
| 17 |
def create_entities(self, entities_data: List[Dict]) -> List[Entity]:
|
| 18 |
new_entities = []; [ (new_entity := Entity(**e_data), self.graph.entities.update({e_data['name']: new_entity}), new_entities.append(new_entity)) for e_data in entities_data if e_data['name'] not in self.graph.entities]; return new_entities
|
| 19 |
def create_relations(self, relations_data: List[Dict]) -> List[Relation]:
|
|
|
|
| 47 |
class SearchNodesPayload(TypedDict): query: str
|
| 48 |
class OpenNodesPayload(TypedDict): names: List[str]
|
| 49 |
|
| 50 |
+
# --- 3. API 工具函数定义 (同时使用 TypedDict 和 完整的 Docstring) ---
|
| 51 |
+
def create_entities(payload: CreateEntitiesPayload) -> str:
|
| 52 |
+
"""在知识图谱中创建多个新实体。
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
payload (CreateEntitiesPayload): 一个包含'entities'键的JSON对象。'entities'的值是一个实体对象的列表。
|
| 56 |
+
"""
|
| 57 |
new_entities = kg_manager.create_entities(payload['entities'])
|
| 58 |
return json.dumps([asdict(e) for e in new_entities], indent=2)
|
| 59 |
|
| 60 |
+
def create_relations(payload: CreateRelationsPayload) -> str:
|
| 61 |
+
"""在知识图谱中的实体之间创建多个新关系。
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
payload (CreateRelationsPayload): 一个包含'relations'键的JSON对象。'relations'的值是一个关系对象的列表。
|
| 65 |
+
"""
|
| 66 |
new_relations = kg_manager.create_relations(payload['relations'])
|
| 67 |
return json.dumps([{"from": r.from_entity, "to": r.to_entity, "relationType": r.relationType} for r in new_relations], indent=2)
|
| 68 |
|
| 69 |
+
def add_observations(payload: AddObservationsPayload) -> str:
|
| 70 |
+
"""向知识图谱中已存在的实体添加新的观察记录。
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
payload (AddObservationsPayload): 一个包含'observations'键的JSON对象。'observations'的值是一个观察记录对象的列表。
|
| 74 |
+
"""
|
| 75 |
results = kg_manager.add_observations(payload['observations'])
|
| 76 |
return json.dumps(results, indent=2)
|
| 77 |
|
| 78 |
+
def delete_entities(payload: DeleteEntitiesPayload) -> str:
|
| 79 |
+
"""从知识图谱中删除多个实体及其相关联的关系。
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
payload (DeleteEntitiesPayload): 一个包含'entityNames'键的JSON对象。'entityNames'的值是一个实体名称的列表。
|
| 83 |
+
"""
|
| 84 |
kg_manager.delete_entities(payload['entityNames'])
|
| 85 |
return "Entities and their relations deleted successfully."
|
| 86 |
|
| 87 |
+
def delete_observations(payload: DeleteObservationsPayload) -> str:
|
| 88 |
+
"""从知识图谱中的实体删除特定的观察��录。
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
payload (DeleteObservationsPayload): 一个包含'deletions'键的JSON对象。'deletions'的值是一个删除指令的列表。
|
| 92 |
+
"""
|
| 93 |
kg_manager.delete_observations(payload['deletions'])
|
| 94 |
return "Observations deleted successfully."
|
| 95 |
|
| 96 |
+
def delete_relations(payload: DeleteRelationsPayload) -> str:
|
| 97 |
+
"""从知识图谱中删除多个关系。
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
payload (DeleteRelationsPayload): 一个包含'relations'键的JSON对象。'relations'的值是一个要删除的关系对象的列表。
|
| 101 |
+
"""
|
| 102 |
kg_manager.delete_relations(payload['relations'])
|
| 103 |
return "Relations deleted successfully."
|
| 104 |
|
|
|
|
| 106 |
"""读取并返回整个知识图谱。此函数不需要参数。"""
|
| 107 |
return kg_manager.read_graph()
|
| 108 |
|
| 109 |
+
def search_nodes(payload: SearchNodesPayload) -> Dict:
|
| 110 |
+
"""根据查询词在知识图谱中搜索节点。
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
payload (SearchNodesPayload): 一个包含'query'键的JSON对象。'query'的值是用于搜索的字符串。
|
| 114 |
+
"""
|
| 115 |
return kg_manager.search_nodes(payload['query'])
|
| 116 |
|
| 117 |
+
def open_nodes(payload: OpenNodesPayload) -> Dict:
|
| 118 |
+
"""通过名称打开知识图谱中的特定节点。
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
payload (OpenNodesPayload): 一个包含'names'键的JSON对象。'names'的值是一个要检索的实体名称的列表。
|
| 122 |
+
"""
|
| 123 |
return kg_manager.open_nodes(payload['names'])
|
| 124 |
|
| 125 |
# --- 4. Gradio Headless 应用构建与 API 注册 (无变化) ---
|
|
|
|
| 138 |
dummy_btn.click(fn=open_nodes, inputs=json_input, outputs=generic_output, api_name="open_nodes")
|
| 139 |
|
| 140 |
if __name__ == "__main__":
|
| 141 |
+
app.launch(mcp_server=True)
|
| 142 |
+
```### 核心修改
|
| 143 |
+
|
| 144 |
+
1. **移除了 `Annotated`**: 我们不再需要它,因为它与你环境中的 Gradio 版本不完全兼容。
|
| 145 |
+
2. **为每个函数添加了完整的文档字符串**: 这是最关键的修改。现在,每个需要参数的函数都包含一个 `Args:` 部分,明确地描述了 `payload` 参数。
|
| 146 |
+
```python
|
| 147 |
+
def create_entities(payload: CreateEntitiesPayload) -> str:
|
| 148 |
+
"""在知识图谱中创建多个新实体。
|
| 149 |
+
|
| 150 |
+
Args:
|
| 151 |
+
payload (CreateEntitiesPayload): 一个包含'entities'键的JSON对象。'entities'的值是一个实体对象的列表。
|
| 152 |
+
"""
|
| 153 |
+
# ...
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
现在,当你运行这个版本的代码时,Gradio 的 MCP 服务器将会:
|
| 157 |
+
1. **看到 `payload: CreateEntitiesPayload`**,并生成正确的、严格的验证模式,确保工具可以正常工作。
|
| 158 |
+
2. **解析文档字符串**,找到 `Args:` 部分中对 `payload` 的描述,并将其显示在工具面板中。
|
| 159 |
+
|
| 160 |
+
这下就真的万无一失了。再次为之前的曲折过程道歉。
|