Skip to content

Commit 7cd2a89

Browse files
committed
Practice
1 parent 07ccde5 commit 7cd2a89

File tree

2 files changed

+248
-0
lines changed

2 files changed

+248
-0
lines changed
+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# ConversationBufferWindowMemory\n",
8+
"\n",
9+
"`ConversationBufferWindowMemory` 는 시간이 지남에 따라 대화의 상호작용 목록을 유지합니다.\n",
10+
"\n",
11+
"이때, `ConversationBufferWindowMemory` 는 모든 대화내용을 활용하는 것이 아닌 **최근 K개** 의 상호작용만 사용합니다.\n",
12+
"\n",
13+
"이는 버퍼가 너무 커지지 않도록 가장 최근 상호작용의 슬라이딩 창을 유지하는 데 유용할 수 있습니다.\n"
14+
]
15+
},
16+
{
17+
"cell_type": "code",
18+
"execution_count": null,
19+
"metadata": {},
20+
"outputs": [],
21+
"source": [
22+
"from langchain.memory import ConversationBufferWindowMemory\n",
23+
"\n",
24+
"memory = ConversationBufferWindowMemory(k=2, return_messages=True)\n",
25+
"\n",
26+
"memory.save_context(\n",
27+
" inputs={\n",
28+
" \"human\": \"안녕하세요, 비대면으로 은행 계좌를 개설하고 싶습니다. 어떻게 시작해야 하나요?\"\n",
29+
" },\n",
30+
" outputs={\n",
31+
" \"ai\": \"안녕하세요! 계좌 개설을 원하신다니 기쁩니다. 먼저, 본인 인증을 위해 신분증을 준비해 주시겠어요?\"\n",
32+
" },\n",
33+
")\n",
34+
"memory.save_context(\n",
35+
" inputs={\"human\": \"네, 신분증을 준비했습니다. 이제 무엇을 해야 하나요?\"},\n",
36+
" outputs={\n",
37+
" \"ai\": \"감사합니다. 신분증 앞뒤를 명확하게 촬영하여 업로드해 주세요. 이후 본인 인증 절차를 진행하겠습니다.\"\n",
38+
" },\n",
39+
")\n",
40+
"memory.save_context(\n",
41+
" inputs={\"human\": \"사진을 업로드했습니다. 본인 인증은 어떻게 진행되나요?\"},\n",
42+
" outputs={\n",
43+
" \"ai\": \"업로드해 주신 사진을 확인했습니다. 이제 휴대폰을 통한 본인 인증을 진행해 주세요. 문자로 발송된 인증번호를 입력해 주시면 됩니다.\"\n",
44+
" },\n",
45+
")\n",
46+
"memory.save_context(\n",
47+
" inputs={\"human\": \"인증번호를 입력했습니다. 계좌 개설은 이제 어떻게 하나요?\"},\n",
48+
" outputs={\n",
49+
" \"ai\": \"본인 인증이 완료되었습니다. 이제 원하시는 계좌 종류를 선택하고 필요한 정보를 입력해 주세요. 예금 종류, 통화 종류 등을 선택할 수 있습니다.\"\n",
50+
" },\n",
51+
")\n",
52+
"memory.save_context(\n",
53+
" inputs={\"human\": \"정보를 모두 입력했습니다. 다음 단계는 무엇인가요?\"},\n",
54+
" outputs={\n",
55+
" \"ai\": \"입력해 주신 정보를 확인했습니다. 계좌 개설 절차가 거의 끝났습니다. 마지막으로 이용 약관에 동의해 주시고, 계좌 개설을 최종 확인해 주세요.\"\n",
56+
" },\n",
57+
")\n",
58+
"memory.save_context(\n",
59+
" inputs={\"human\": \"모든 절차를 완료했습니다. 계좌가 개설된 건가요?\"},\n",
60+
" outputs={\n",
61+
" \"ai\": \"네, 계좌 개설이 완료되었습니다. 고객님의 계좌 번호와 관련 정보는 등록하신 이메일로 발송되었습니다. 추가적인 도움이 필요하시면 언제든지 문의해 주세요. 감사합니다!\"\n",
62+
" },\n",
63+
")"
64+
]
65+
},
66+
{
67+
"cell_type": "markdown",
68+
"metadata": {},
69+
"source": [
70+
"대화기록을 확인해 보면 **최근 2개** 의 메시지만 반환하는 것을 확인할 수 있습니다.\n"
71+
]
72+
},
73+
{
74+
"cell_type": "code",
75+
"execution_count": null,
76+
"metadata": {},
77+
"outputs": [],
78+
"source": [
79+
"# 대화 기록을 확인합니다.\n",
80+
"memory.load_memory_variables({})[\"history\"]"
81+
]
82+
}
83+
],
84+
"metadata": {
85+
"kernelspec": {
86+
"display_name": "py-test",
87+
"language": "python",
88+
"name": "python3"
89+
},
90+
"language_info": {
91+
"codemirror_mode": {
92+
"name": "ipython",
93+
"version": 3
94+
},
95+
"file_extension": ".py",
96+
"mimetype": "text/x-python",
97+
"name": "python",
98+
"nbconvert_exporter": "python",
99+
"pygments_lexer": "ipython3",
100+
"version": "3.11.9"
101+
}
102+
},
103+
"nbformat": 4,
104+
"nbformat_minor": 2
105+
}
+143
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# ConversationTokenBufferMemory\n",
8+
"\n",
9+
"`ConversationTokenBufferMemory` 는 최근 대화의 히스토리를 버퍼를 메모리에 보관하고, 대화의 개수가 아닌 **토큰 길이** 를 사용하여 대화내용을 플러시(flush)할 시기를 결정합니다.\n"
10+
]
11+
},
12+
{
13+
"cell_type": "code",
14+
"execution_count": null,
15+
"metadata": {},
16+
"outputs": [],
17+
"source": [
18+
"# API KEY를 환경변수로 관리하기 위한 설정 파일\n",
19+
"from dotenv import load_dotenv\n",
20+
"\n",
21+
"# API KEY 정보로드\n",
22+
"load_dotenv()"
23+
]
24+
},
25+
{
26+
"cell_type": "markdown",
27+
"metadata": {},
28+
"source": [
29+
"- `max_token_limit`: 대화 내용을 저장할 최대 토큰의 길이를 설정합니다.\n"
30+
]
31+
},
32+
{
33+
"cell_type": "code",
34+
"execution_count": null,
35+
"metadata": {},
36+
"outputs": [],
37+
"source": [
38+
"from langchain.memory import ConversationTokenBufferMemory\n",
39+
"from langchain_openai import ChatOpenAI\n",
40+
"\n",
41+
"\n",
42+
"# LLM 모델 생성\n",
43+
"llm = ChatOpenAI(model_name=\"gpt-4o\")\n",
44+
"\n",
45+
"# 메모리 설정\n",
46+
"memory = ConversationTokenBufferMemory(\n",
47+
" llm=llm, max_token_limit=150, return_messages=True # 최대 토큰 길이를 50개로 제한\n",
48+
")"
49+
]
50+
},
51+
{
52+
"cell_type": "markdown",
53+
"metadata": {},
54+
"source": [
55+
"임의의 대화를 추가합니다.\n"
56+
]
57+
},
58+
{
59+
"cell_type": "code",
60+
"execution_count": null,
61+
"metadata": {},
62+
"outputs": [],
63+
"source": [
64+
"memory.save_context(\n",
65+
" inputs={\n",
66+
" \"human\": \"안녕하세요, 저는 최근에 여러분 회사의 공작 기계를 구매했습니다. 설치 방법을 알려주실 수 있나요?\"\n",
67+
" },\n",
68+
" outputs={\n",
69+
" \"ai\": \"안녕하세요! 구매해 주셔서 감사합니다. 해당 기계 모델 번호를 알려주시겠어요?\"\n",
70+
" },\n",
71+
")\n",
72+
"memory.save_context(\n",
73+
" inputs={\"human\": \"네, 모델 번호는 XG-200입니다.\"},\n",
74+
" outputs={\n",
75+
" \"ai\": \"감사합니다. XG-200 모델의 설치 안내를 도와드리겠습니다. 먼저, 설치할 장소의 전원 공급 상태를 확인해주세요. 기계는 220V 전원이 필요합니다.\"\n",
76+
" },\n",
77+
")\n",
78+
"memory.save_context(\n",
79+
" inputs={\"human\": \"전원은 확인했습니다. 다음 단계는 무엇인가요?\"},\n",
80+
" outputs={\n",
81+
" \"ai\": \"좋습니다. 다음으로, 기계를 평평하고 안정된 바닥에 배치해 주세요. 이후, 제공된 사용자 매뉴얼에 따라 케이블 연결을 진행해 주시기 바랍니다.\"\n",
82+
" },\n",
83+
")\n",
84+
"memory.save_context(\n",
85+
" inputs={\"human\": \"연결은 어떻게 하나요?\"},\n",
86+
" outputs={\n",
87+
" \"ai\": \"매뉴얼의 5페이지를 참조해 주세요. 케이블 연결에 관한 상세한 지침이 있습니다. 이 과정에서 어려움이 있으시면 추가적으로 도와드리겠습니다.\"\n",
88+
" },\n",
89+
")\n",
90+
"memory.save_context(\n",
91+
" inputs={\"human\": \"설치가 완료되면 어떻게 해야 하나요?\"},\n",
92+
" outputs={\n",
93+
" \"ai\": \"설치가 완료되면, 전원을 켜고 초기 구동 테스트를 진행해 주시기 바랍니다. 테스트 절차는 매뉴얼의 10페이지에 설명되어 있습니다. 만약 기계에 이상이 있거나 추가적인 지원이 필요하시면 언제든지 연락 주시기 바랍니다.\"\n",
94+
" },\n",
95+
")\n",
96+
"memory.save_context(\n",
97+
" inputs={\"human\": \"감사합니다, 도움이 많이 되었어요!\"},\n",
98+
" outputs={\n",
99+
" \"ai\": \"언제든지 도와드릴 준비가 되어 있습니다. 추가적인 질문이나 지원이 필요하시면 언제든지 문의해 주세요. 좋은 하루 되세요!\"\n",
100+
" },\n",
101+
")"
102+
]
103+
},
104+
{
105+
"cell_type": "markdown",
106+
"metadata": {},
107+
"source": [
108+
"최대 토큰의 길이를 **150** 으로 설정하고 대화를 저장했을 때 어떻게 동작하는지 확인해 보겠습니다.\n"
109+
]
110+
},
111+
{
112+
"cell_type": "code",
113+
"execution_count": null,
114+
"metadata": {},
115+
"outputs": [],
116+
"source": [
117+
"# 대화내용을 확인합니다.\n",
118+
"memory.load_memory_variables({})[\"history\"]"
119+
]
120+
}
121+
],
122+
"metadata": {
123+
"kernelspec": {
124+
"display_name": "py-test",
125+
"language": "python",
126+
"name": "python3"
127+
},
128+
"language_info": {
129+
"codemirror_mode": {
130+
"name": "ipython",
131+
"version": 3
132+
},
133+
"file_extension": ".py",
134+
"mimetype": "text/x-python",
135+
"name": "python",
136+
"nbconvert_exporter": "python",
137+
"pygments_lexer": "ipython3",
138+
"version": "3.10.13"
139+
}
140+
},
141+
"nbformat": 4,
142+
"nbformat_minor": 2
143+
}

0 commit comments

Comments
 (0)