1. ChatGPT 客服对话

1.1 代码

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
import ollama

# 创建指向本地服务器的客户端
client = ollama.Client(host='http://192.168.100.135:11434')


def customer_service_chat(history: str, user_input: str, max_turns: int = 3) -> tuple[str, str]:
"""
与客服进行对话,并维护对话历史。

参数:
history (str): 先前的对话历史。
user_input (str): 用户当前的输入。
max_turns (int): 需要保留的最大对话轮数。

返回:
tuple[str, str]: 更新后的对话历史和客服的回复。
"""
# 分割历史对话成列表,保留最近 max_turns 轮对话
history_lines = history.split("\n")
recent_history = "\n".join(history_lines[-max_turns * 2:]) # 每轮对话包含用户和客服两句

# 更新历史记录,拼接对话
recent_history += f"\n用户: {user_input}\n客服:"

# 使用 Ollama 进行对话,要求用中文回答,并明确指示上下文
messages = [
{'role': 'system', 'content': '请根据以下对话历史,用中文回答问题。'},
{'role': 'user', 'content': recent_history}
]

response = client.chat(model='llama3.2:1b', messages=messages)

# 提取并清理模型的回复
reply = response['message']['content'].strip()

# 更新历史,保留全量历史记录
history += f"\n用户: {user_input}\n客服: {reply}"

return history, reply


# 示例对话
history = "客服: 欢迎使用在线客服系统!请问有什么可以帮您?"
user_input = "我想预订一张飞往纽约的机票。"
history, reply = customer_service_chat(history, user_input)
print(f"用户: {user_input}\n客服: {reply}\n")

user_input = "有哪些航班可以选择?"
history, reply = customer_service_chat(history, user_input)
print(f"用户: {user_input}\n客服: {reply}")

1.2 输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
用户: 我想预订一张飞往纽约的机票。
客服: 客服:好的,您想预订一张飞往纽约的机票,请提供您的旅行信息,如 travelers.name、travelers.email、travelers_phone_number、departure_date、destination_airport等。

用户: 有哪些航班可以选择?
客服: 客服:谢谢你的提问!您想要预订一张飞往纽约的机票,我们有许多选项可供选择。具体到您需要的 Flight Number、Departure Date 和 Destination Airport,我们可以提供以下几种航班:

*Flight 123:从新泽西州特雷维斯郡的波士顿国际机场(BOS)飞往纽约肯德尔国际机场(JFK), Departure Date:2024年1月5日, Arrival Time:22:00,价格为 $200。
* Flight 456:从加拿大安省的一个市镇飞往纽约的波士顿国际机场, Departure Date:2024年2月12日, Arrival Time:20:30,价格为 $250。

我们也可以提供更多选项,例如:

*Flight 901:从新泽西州特雷维斯郡的波士顿国际机场飞往纽约的肯德尔国际机场, Departure Date:2024年3月15日, Arrival Time:01:00,价格为 $300。
* Flight 234:从加拿大安省的一个市镇飞往纽约的波士顿国际机场, Departure Date:2024年4月10日, Arrival Time:19:30,价格为 $280。

我们提供所有这些航班,你可以选择您需要的。

2. 对话压缩

2.1 代码

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
import ollama

def summarize_dialogue(dialogue_history):
    # 历史对话压缩,提取关键信息
    relevant_dialogue = "\n".join(line for line in dialogue_history.split("\n") if "用户:" in line or "客服:" in line)
    
    # 生成对话摘要的提示词,强调保留数字和地点等关键信息
    prompt = (
        f"请提取以下对话的关键信息,并生成摘要,保留数字和地点等重要信息,去除不必要的细节:\n\n{relevant_dialogue}"
    )
    
    # 使用 Ollama 进行对话摘要生成,并指定用中文回答
    messages = [
        {'role': 'user', 'content': prompt},
        {'role': 'system', 'content': '请用中文回答'}
    ]
    
    response = ollama.chat(model='llama3', messages=messages)

    # 提取并清理模型的回复
    summary = response['message']['content'].strip()
    
    return summary

# 示例对话记录
dialogue_history = (
    "用户: 你好,你怎么样?\n"
    "客服: 我很好,谢谢!请问今天有什么可以帮助您的?\n"
    "用户: 我需要帮助处理我的账户。您能查看我的余额吗?\n"
    "客服: 当然可以!请提供您的账户号码。\n"
    "用户: 我的账户号码是123456。\n"
    "客服: 让我为您查一下...\n"
    "客服: 您的当前余额是$500。\n"
    "用户: 谢谢!您能告诉我最近的交易吗?\n"
    "客服: 我需要验证您的身份才能提供交易详细信息。\n"
    "用户: 好的,这里是我有的详细信息。\n"
)

# 生成摘要
summary = summarize_dialogue(dialogue_history)
print("对话摘要:", summary)

# 压缩历史对话信息
dialogue_history = summary

2.2 输出

1
2
3
4
5
6
7
8
9
10
11
12
对话摘要:
<|start_header_id|>assistant<|end_header_id|>

关键信息:

* 通过电话联系客服获得帮助
* 需要提供账户号码进行余额查找
* 账户余额为 $500
* 需要验证身份才能获取交易历史

摘要:
用户需要助理,客服同意为其查找余额,并要求提供账户号码。经过 verify 的过程,用户的余额显示为 $500。

3. 有限状态机(FSM)任务流程建模

3.1 代码

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
import json
import ollama

# 创建指向本地服务器的客户端
client = ollama.Client(host='http://192.168.100.135:11434')

class FinancialProductFSM:
def __init__(self):
self.states = {
'START': 'START',
'YOUNG': 'YOUNG',
'OLD': 'OLD',
'LOW_RISK': 'LOW_RISK',
'HIGH_RISK': 'HIGH_RISK',
'HIGH_INCOME': 'HIGH_INCOME',
'LOW_INCOME': 'LOW_INCOME'
}
self.current_state = self.states['START']

self.transitions = {
(self.states['START'], 'young'): self.states['YOUNG'],
(self.states['START'], 'old'): self.states['OLD'],
(self.states['YOUNG'], 'low_risk'): self.states['LOW_RISK'],
(self.states['YOUNG'], 'high_risk'): self.states['HIGH_RISK'],
(self.states['OLD'], 'low_risk'): self.states['LOW_RISK'],
(self.states['OLD'], 'high_risk'): self.states['HIGH_RISK'],
}

self.product_recommendations = {
(self.states['LOW_RISK'], self.states['HIGH_INCOME']): '高收益储蓄账户',
(self.states['HIGH_RISK'], self.states['HIGH_INCOME']): '股票和共同基金',
(self.states['LOW_RISK'], self.states['LOW_INCOME']): '定期存款(CD)',
(self.states['HIGH_RISK'], self.states['LOW_INCOME']): '高风险投资基金',
}

def process_input(self, user_info):
age = user_info.get('age')
risk = user_info.get('risk')
income = user_info.get('income')

new_state = self.update_state(age, risk)
if new_state is None:
return '输入无效'

self.current_state = new_state
return self.get_recommendation(income)

def update_state(self, age, risk):
if age in ['young', 'old']:
state_after_age = self.transitions.get((self.states['START'], age))
return self.transitions.get((state_after_age, risk)) if state_after_age else None
return None

def get_recommendation(self, income):
for (risk_state, income_state), product in self.product_recommendations.items():
if self.current_state == risk_state:
return product if income_state == (self.states['HIGH_INCOME'] if income == 'high_income' else self.states['LOW_INCOME']) else None
return '没有合适的产品推荐'

def get_user_info_from_ollama(dialogue):
"""
与 Ollama 模型对话,要求返回用户的关键信息,以 JSON 格式返回。
指定 age、risk、income 的可能枚举值。
"""
prompt = f"""
请从以下对话中提取用户的年龄、风险偏好和收入水平,并以 JSON 格式返回。只输出 JSON,不要附加任何其他文字。
格式如下:
{{
"age": "young" 或 "old",
"risk": "low_risk" 或 "high_risk",
"income": "high_income" 或 "low_income"
}}

对话内容如下:
{dialogue}
"""

# 调用 Ollama API 进行对话,返回结构化的 JSON 响应
response = client.chat(model='llama3.2:1b', messages=[{'role': 'user', 'content': prompt}])

# 获取 Ollama 返回的响应
ollama_response = response['message']['content'].strip()

# 将响应字符串转换为 Python 字典
try:
user_info = json.loads(ollama_response) # 使用 json.loads 安全解析 JSON
except json.JSONDecodeError:
return None

return user_info

def main():
fsm = FinancialProductFSM()
print("欢迎来到金融产品推荐系统!")

# 假设对话记录来自 Ollama 的自然语言对话
dialogue_history = """
用户: 我年轻,喜欢高风险投资,而且收入挺高的。
"""

# 使用 Ollama 提取用户信息(年龄、风险偏好、收入水平)
user_info = get_user_info_from_ollama(dialogue_history)

if user_info:
# 显示提取的用户信息
print(f"提取的用户信息: {json.dumps(user_info, ensure_ascii=False)}")

# 处理提取的信息并推荐金融产品
recommendation = fsm.process_input(user_info)
print(f"推荐的产品: {recommendation}")
else:
print("无法根据用户输入生成推荐。")

if __name__ == "__main__":
main()

3.2 输出

1
2
3
欢迎来到金融产品推荐系统!
提取的用户信息: {"age": "young", "risk": "high_risk", "income": "high_income"}
推荐的产品: 股票和共同基金

本站由 卡卡龙 使用 Stellar 1.29.1主题创建

本站访问量 次. 本文阅读量 次.