Skip to content

Commit 3d3334b

Browse files
committed
Practice
1 parent 7cd2a89 commit 3d3334b

3 files changed

+271
-0
lines changed

Diff for: .gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.env

Diff for: 02-ConversationBufferWindowMemory_eng.ipynb

+127
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# ConversationBufferWindowMemory\n",
8+
"\n",
9+
"`ConversationBufferWindowMemory` maintains a list of interactions over time.\n",
10+
"\n",
11+
"At this time, `ConversationBufferWindowMemory` uses only the **most recent K** interactions, not all conversation content.\n",
12+
"\n",
13+
"This can be useful for maintaining a sliding window of the most recent interactions so that the buffer does not become too large.\n",
14+
"\n"
15+
]
16+
},
17+
{
18+
"cell_type": "code",
19+
"execution_count": 1,
20+
"metadata": {},
21+
"outputs": [],
22+
"source": [
23+
"from langchain.memory import ConversationBufferWindowMemory\n",
24+
"\n",
25+
"memory = ConversationBufferWindowMemory(k=2, return_messages=True)\n",
26+
"\n",
27+
"memory.save_context(\n",
28+
" inputs={\n",
29+
" \"human\": \"Hello, I would like to open a bank account online. How should I start?\"\n",
30+
" },\n",
31+
" outputs={\n",
32+
" \"ai\": \"Hello! I'm glad you want to open an account. First, could you please prepare your ID for verification?\"\n",
33+
" },\n",
34+
")\n",
35+
"memory.save_context(\n",
36+
" inputs={\"human\": \"Yes, I have prepared my ID. What should I do next?\"},\n",
37+
" outputs={\n",
38+
" \"ai\": \"Thank you. Please take a clear photo of the front and back of your ID and upload it. We will proceed with the verification process afterward.\"\n",
39+
" },\n",
40+
")\n",
41+
"memory.save_context(\n",
42+
" inputs={\"human\": \"I have uploaded the photo. How is the verification done?\"},\n",
43+
" outputs={\n",
44+
" \"ai\": \"We have checked the photo you uploaded. Now, please proceed with the verification through your phone. Enter the verification code sent via text message.\"\n",
45+
" },\n",
46+
")\n",
47+
"memory.save_context(\n",
48+
" inputs={\"human\": \"I have entered the verification code. How do I open the account now?\"},\n",
49+
" outputs={\n",
50+
" \"ai\": \"Your verification is complete. Now, please select the type of account you want and enter the necessary information. You can choose the type of deposit, currency, etc.\"\n",
51+
" },\n",
52+
")\n",
53+
"memory.save_context(\n",
54+
" inputs={\"human\": \"I have entered all the information. What is the next step?\"},\n",
55+
" outputs={\n",
56+
" \"ai\": \"We have checked the information you entered. The account opening process is almost complete. Finally, please agree to the terms and conditions and confirm the account opening.\"\n",
57+
" },\n",
58+
")\n",
59+
"memory.save_context(\n",
60+
" inputs={\"human\": \"I have completed all the procedures. Is the account opened?\"},\n",
61+
" outputs={\n",
62+
" \"ai\": \"Yes, the account has been opened. Your account number and related information have been sent to your registered email. If you need further assistance, please feel free to contact us. Thank you!\"\n",
63+
" },\n",
64+
")"
65+
]
66+
},
67+
{
68+
"cell_type": "markdown",
69+
"metadata": {},
70+
"source": [
71+
"You can check the conversation history to see that it returns only the **most recent 2** messages.\n"
72+
]
73+
},
74+
{
75+
"cell_type": "code",
76+
"execution_count": 4,
77+
"metadata": {},
78+
"outputs": [
79+
{
80+
"data": {
81+
"text/plain": [
82+
"[HumanMessage(content='I have entered all the information. What is the next step?', additional_kwargs={}, response_metadata={}),\n",
83+
" AIMessage(content='We have checked the information you entered. The account opening process is almost complete. Finally, please agree to the terms and conditions and confirm the account opening.', additional_kwargs={}, response_metadata={}),\n",
84+
" HumanMessage(content='I have completed all the procedures. Is the account opened?', additional_kwargs={}, response_metadata={}),\n",
85+
" AIMessage(content='Yes, the account has been opened. Your account number and related information have been sent to your registered email. If you need further assistance, please feel free to contact us. Thank you!', additional_kwargs={}, response_metadata={})]"
86+
]
87+
},
88+
"execution_count": 4,
89+
"metadata": {},
90+
"output_type": "execute_result"
91+
}
92+
],
93+
"source": [
94+
"# Check the conversation history.\n",
95+
"memory.load_memory_variables({})[\"history\"]"
96+
]
97+
},
98+
{
99+
"cell_type": "code",
100+
"execution_count": null,
101+
"metadata": {},
102+
"outputs": [],
103+
"source": []
104+
}
105+
],
106+
"metadata": {
107+
"kernelspec": {
108+
"display_name": "py-test",
109+
"language": "python",
110+
"name": "python3"
111+
},
112+
"language_info": {
113+
"codemirror_mode": {
114+
"name": "ipython",
115+
"version": 3
116+
},
117+
"file_extension": ".py",
118+
"mimetype": "text/x-python",
119+
"name": "python",
120+
"nbconvert_exporter": "python",
121+
"pygments_lexer": "ipython3",
122+
"version": "3.11.10"
123+
}
124+
},
125+
"nbformat": 4,
126+
"nbformat_minor": 2
127+
}

Diff for: 03-ConversationTokenBufferMemory_eng.ipynb

+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)