intent_client.py
4.37 KB
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
import os
import requests
from typing import Any, Dict, Optional
class IntentFusionClient:
"""
Client for interacting with the Intent Fusion Service.
Allows uploading custom intent configuration YAMLs and querying intents.
"""
def __init__(self, base_url: str = "http://127.0.0.1:8000"):
self.base_url = base_url.rstrip('/')
def upload_intents(self, name: str, yaml_content_or_path: str) -> Dict[str, Any]:
"""
Uploads a custom YAML intent configuration to the service.
Args:
name: The name/identifier of your dataset/custom config (e.g. 'glsx_json').
yaml_content_or_path: Either the raw YAML content string or a path to a local YAML file.
Returns:
The server response payload, e.g. {"ok": True, "dataset": "uploads/<name>"}
"""
# Check if the input is a valid file path, if so read its content
if os.path.isfile(yaml_content_or_path):
with open(yaml_content_or_path, 'r', encoding='utf-8') as f:
yaml_content = f.read()
else:
yaml_content = yaml_content_or_path
url = f"{self.base_url}/api/intents/upload"
payload = {
"name": name,
"yaml_content": yaml_content
}
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()
def fuse(self, message: str, dataset: str, alpha: Optional[float] = None, delta: Optional[float] = None) -> Dict[str, Any]:
"""
Sends a query message to be classified by the specified dataset.
Args:
message: The user query string (e.g. "门店运营数量").
dataset: The dataset key/name (e.g. "glsx_json").
alpha: Optional float override for fusion weight (hybrid scoring).
delta: Optional float override for fusion threshold (decision logic).
Returns:
The classification result including the top intent, candidates, and verdict.
"""
url = f"{self.base_url}/api/fuse"
payload = {
"message": message,
"dataset": dataset
}
if alpha is not None:
payload["alpha"] = alpha
if delta is not None:
payload["delta"] = delta
response = requests.post(url, json=payload)
response.raise_for_status()
return response.json()
def get_top_intent(self, message: str, dataset: str) -> Optional[str]:
"""
Helper method to perform query and directly return the top predicted intent name.
Returns:
The name of the top intent, or None if no intent matched.
"""
res = self.fuse(message, dataset)
top = res.get("top")
if top:
return top.get("name")
return None
# Simple executable demo
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Intent Fusion CLI Client")
parser.add_argument("--url", default="http://127.0.0.1:8000", help="Service Base URL")
parser.add_argument("--upload", help="Path to intents.yaml to upload")
parser.add_argument("--name", help="Dataset/Config name for the uploaded file")
parser.add_argument("--query", help="Text query to test classification")
parser.add_argument("--dataset", help="Dataset name to query against")
args = parser.parse_args()
client = IntentFusionClient(args.url)
try:
if args.upload:
if not args.name:
print("Error: --name is required when uploading a dataset.")
exit(1)
print(f"Uploading file '{args.upload}' as dataset '{args.name}'...")
res = client.upload_intents(args.name, args.upload)
print("Response:", res)
if args.query:
dataset = args.dataset or args.name
if not dataset:
print("Error: --dataset is required to execute a query.")
exit(1)
print(f"Querying '{args.query}' against dataset '{dataset}'...")
res = client.fuse(args.query, dataset)
print("Verdict:", res.get("verdict"))
print("Top Intent:", res.get("top"))
print("Resolved Intents:", res.get("resolved"))
except Exception as e:
print("An error occurred:", e)