-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat_simple.py
More file actions
166 lines (138 loc) · 5.7 KB
/
chat_simple.py
File metadata and controls
166 lines (138 loc) · 5.7 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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
"""
Generative AI Platform でチャットルームなしのシンプルな会話を行うサンプルコード。
このサンプルコードは、Simple Chat API を使用してチャットルームを作成せずに
直接 AI との会話を行います。
以下の機能が含まれています。
- 7.5.1. チャットルームなしで会話を行う(SimpleChat Call): チャットルームを使わずに会話を実行
"""
import requests
import msal
import json
import os
import urllib3
from dotenv import load_dotenv
class GAPSimpleChatClient:
def __init__(self, tenant_name, client_id, endpoint):
self.tenant_name = tenant_name
self.client_id = client_id
self.endpoint = endpoint
self.authority = f"https://{tenant_name}.b2clogin.com/{tenant_name}.onmicrosoft.com/b2c_1_fjcloud_genai_susi"
self.scopes = []
self.access_token_cache = msal.SerializableTokenCache()
self.client = msal.PublicClientApplication(
client_id, authority=self.authority, token_cache=self.access_token_cache
)
self.access_token = self._get_access_token()
self.headers = {
"accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {self.access_token}",
}
def _get_access_token(self):
result = None
accounts = self.client.get_accounts()
if accounts:
result = self.client.acquire_token_silent(self.scopes, accounts[0])
else:
result = self.client.acquire_token_interactive(
self.scopes, prompt="select_account"
)
return result["id_token"]
def simple_chat(
self,
question,
model="cohere.command-r-plus-fujitsu",
max_tokens=1024,
temperature=0.5,
top_p=1.0,
messages=None,
):
"""
チャットルームなしでシンプルな会話を行う
Args:
question (str): 会話内容(質問)
model (str): 使用する言語モデル
max_tokens (int): 最大トークン数
temperature (float): 予測不可能性(0.0~1.0)
top_p (float): 回答範囲(0.0~1.0)
messages (list): 過去の会話履歴(省略可)
Returns:
dict: API レスポンス(answer と messages を含む)
"""
url = f"{self.endpoint}/api/v1/action/defined/text:simple_chat/call"
if messages is None:
messages = []
body = {
"max_tokens": max_tokens,
"messages": messages,
"model": model,
"question": question,
"temperature": temperature,
"top_p": top_p,
}
response = requests.post(url, headers=self.headers, json=body, verify=False)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
load_dotenv()
tenant_name = os.getenv("TENANT_NAME")
client_id = os.getenv("CLIENT_ID")
endpoint = f"https://{tenant_name}.generative-ai-platform.cloud.global.fujitsu.com"
client = GAPSimpleChatClient(tenant_name, client_id, endpoint)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# --- 7.5.1. チャットルームなしで会話を行う(単発の質問)---
print("=== 単発の質問 ===")
question = "自己紹介をしてください"
response = client.simple_chat(question=question)
print(f"質問: {question}")
print(f"回答:\n{response['answer']}\n")
# --- 過去の会話を含めた質問 ---
print("=== 過去の会話を含めた質問 ===")
# 1回目の会話
question1 = "私の名前は太郎です。"
response1 = client.simple_chat(question=question1)
print(f"ユーザー: {question1}")
print(f"AI: {response1['answer']}\n")
# 2回目の会話(過去の会話履歴を含める)
conversation_history = [
{"role": "user", "content": question1},
{"role": "ai", "content": response1["answer"]},
]
question2 = "私の名前を覚えていますか?"
response2 = client.simple_chat(question=question2, messages=conversation_history)
print(f"ユーザー: {question2}")
print(f"AI: {response2['answer']}\n")
# --- パラメータをカスタマイズした例 ---
print("=== パラメータカスタマイズ(創造的な回答)===")
question3 = "冬の朝について短い詩を作ってください。"
response3 = client.simple_chat(
question=question3,
max_tokens=512,
temperature=0.9, # より創造的な回答
top_p=0.95,
)
print(f"質問: {question3}")
print(f"回答:\n{response3['answer']}\n")
# --- 複数ターンの会話 ---
print("=== 複数ターンの会話 ===")
conversation = []
# 1ターン目
q1 = "Pythonのリスト内包表記について教えてください。"
r1 = client.simple_chat(question=q1)
print(f"ユーザー: {q1}")
print(f"AI: {r1['answer']}\n")
conversation.append({"role": "user", "content": q1})
conversation.append({"role": "ai", "content": r1["answer"]})
# 2ターン目
q2 = "具体的な例を見せてください。"
r2 = client.simple_chat(question=q2, messages=conversation)
print(f"ユーザー: {q2}")
print(f"AI: {r2['answer']}\n")
conversation.append({"role": "user", "content": q2})
conversation.append({"role": "ai", "content": r2["answer"]})
# 3ターン目
q3 = "ありがとうございます!"
r3 = client.simple_chat(question=q3, messages=conversation)
print(f"ユーザー: {q3}")
print(f"AI: {r3['answer']}\n")
print("=== サンプル実行完了 ===")