├── .gitignore ├── LICENSE ├── README.md ├── content ├── intro │ ├── hotel_checkin.json │ ├── job_interview.json │ ├── renting.json │ └── salary_negotiation.json └── page │ ├── hotel_checkin.md │ ├── job_interview.md │ ├── renting.md │ ├── salary_negotiation.md │ └── vocab_study.md ├── images ├── gradio.png ├── gradio_0.png └── gradio_1.png ├── prompts ├── conversation_prompt.txt ├── hotel_checkin_prompt.txt ├── job_interview_prompt.txt └── vocab_study_prompt.txt ├── requirements.txt └── src ├── agents ├── __init__.py ├── agent_base.py ├── conversation_agent.py ├── scenario_agent.py ├── session_history.py └── vocab_agent.py ├── main.py ├── tabs ├── conversation_tab.py ├── scenario_tab.py └── vocab_tab.py └── utils ├── logger.py └── merge_requirements.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | 164 | jupyter/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LanguageMentor 2 | 3 | LanguageMentor 是一款基于 LLaMA 3.1 或 GPT-4o-mini 的在线英语私教系统,提供英语对话练习和场景化学习训练。用户可以选择不同的场景,或直接与对话代理人进行自由对话,模拟真实生活中的英语交流场景,提升语言能力。 4 | 5 | 6 | ## 产品设计 7 | 8 | - 核心功能: 9 | - 基础教学:涵盖词汇积累、语法学习、阅读理解和写作技巧等基础内容。 10 | - 对话式训练:模拟真实场景的对话练习,提升学生的口语表达能力和听力理解能力。 11 | - 用户学习路径: 12 | - 初学者:注重词汇和基础语法的学习,通过简单对话练习提高自信心。 13 | - 中级学员:结合复杂语法和高级词汇,进行更深入的阅读和写作训练。 14 | - 高级学员:重点练习口语和听力,通过模拟真实场景的对话提升实战能力。 15 | - 课程设计: 16 | - 词汇积累:采用词根词缀法和常用词汇表,帮助学生高效记忆单词。 17 | - 语法学习:通过系统的语法讲解和练习,夯实学生的语法基础。 18 | - 阅读理解:提供不同难度的阅读材料,训练学生的阅读速度和理解能力。 19 | - 写作技巧:指导学生如何进行段落和文章的结构化写作。 20 | 21 | ## 产品演示 22 | 23 | https://github.com/user-attachments/assets/6298a8e4-28fc-4a60-badc-59bff16b315e 24 | 25 | 26 | ## 快速开始 27 | 以下是快速开始使用 LanguageMentor 的步骤: 28 | 29 | 1. **克隆仓库** 30 | ```bash 31 | git clone https://github.com/DjangoPeng/LanguageMentor.git 32 | cd LanguageMentor 33 | ``` 34 | 35 | 2. **创建 Python 虚拟环境** 36 | 使用 miniconda 或类似 Python 虚拟环境管理工具,创建一个项目专属的环境,取名为`lm`: 37 | ```bash 38 | conda create -n lm python=3.10 39 | ``` 40 | 激活虚拟环境 41 | ```bash 42 | conda activate lm 43 | ``` 44 | 45 | 3. **配置开发环境** 46 | 然后运行以下命令安装所需依赖: 47 | ```bash 48 | pip install -r requirements.txt 49 | ``` 50 | 51 | 根据需要配置你的环境变量,例如 `OpenAI_API_KEY` 等。 52 | 53 | 4. **运行应用** 54 | 启动应用程序: 55 | ```bash 56 | python src/main.py 57 | ``` 58 | 59 | 5. **开始体验** 60 | 打开浏览器,访问 `http://localhost:7860`,开始跟着 LanguageMentor 一起学习英语! 61 | 62 | 运行画面: 63 | ![gradio_demo](images/gradio.png) 64 | 65 | 对话练习: 66 | ![gradio_demo_0](images/gradio_0.png) 67 | ![gradio_demo_1](images/gradio_1.png) 68 | 69 | 70 | ## 贡献 71 | 欢迎对本项目做出贡献!你可以通过以下方式参与: 72 | - 提交问题(Issues)和功能请求 73 | - 提交拉取请求(Pull Requests) 74 | - 参与讨论和提供反馈 75 | 76 | ## 许可证 77 | 本项目采用 Apache 2.0 许可证,详情请参阅 [LICENSE](LICENSE) 文件。 78 | 79 | ## 联系我们 80 | 81 | 如果你有任何问题或建议,请通过以下方式联系我: 82 | - Email: pjt73651@gmail.com 83 | - GitHub Issues: https://github.com/DjangoPeng/LanguageMentor/issues 84 | -------------------------------------------------------------------------------- /content/intro/hotel_checkin.json: -------------------------------------------------------------------------------- 1 | [ 2 | "Good afternoon! How may I assist you today?", 3 | "Welcome to our hotel! Do you have a reservation with us?", 4 | "Hello! Are you here to check in?", 5 | "Hi there! How can I help you with your stay?", 6 | "Good evening! May I have your name for the booking, please?" 7 | ] -------------------------------------------------------------------------------- /content/intro/job_interview.json: -------------------------------------------------------------------------------- 1 | [ 2 | "So, you're here for the R&D Engineer position today?", 3 | "Can I confirm that you've applied for the Research and Development role we have available?", 4 | "You are indeed the candidate we invited to interview for our R&D team, right?", 5 | "I just want to make sure - you are here for the Software Engineer position in our R&D department, correct?", 6 | "Can I confirm that you're the [名字] who applied for the R&D Engineer role at our company?" 7 | ] -------------------------------------------------------------------------------- /content/intro/renting.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/content/intro/renting.json -------------------------------------------------------------------------------- /content/intro/salary_negotiation.json: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/content/intro/salary_negotiation.json -------------------------------------------------------------------------------- /content/page/hotel_checkin.md: -------------------------------------------------------------------------------- 1 | **目标:** 2 | - 完成酒店入住流程并询问酒店的设施(Complete the hotel check-in process and ask about the hotel's amenities) 3 | 4 | **挑战:** 5 | 1. 提供你的预订信息并进行身份验证 6 | Provide your booking information and verify your identity. 7 | 2. 向前台提出房间偏好或需求 8 | Request room preferences or specific needs from the front desk. 9 | 3. 询问酒店的设施(如餐厅、游泳池、健身房等) 10 | Ask about the hotel's amenities (e.g., restaurant, pool, gym). 11 | 4. 向前台询问附近餐馆或娱乐地点的推荐 12 | Ask the front desk for recommendations for nearby restaurants or entertainment venues. -------------------------------------------------------------------------------- /content/page/job_interview.md: -------------------------------------------------------------------------------- 1 | **目标:** 2 | - 自我介绍并回答面试问题(Introduce yourself and answer interview questionss) 3 | 4 | **挑战:** 5 | 1. 告诉面试官你的教育和工作经历 6 | Tell the interviewer about your education and work experience 7 | 2. 回答有关你的优点和缺点的问题 8 | Answer questions about your strengths and weaknesses 9 | 3. 讨论你的职业目标,以及它们如何与公司的使命相一致 10 | Discuss your career goals and how they alignwith the companys mission 11 | 4. 向面试官询问公司文化和公司内部的发展机会 12 | Ask the interviewer about the company cultureand opportunities for growth within the company. -------------------------------------------------------------------------------- /content/page/renting.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/content/page/renting.md -------------------------------------------------------------------------------- /content/page/salary_negotiation.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/content/page/salary_negotiation.md -------------------------------------------------------------------------------- /content/page/vocab_study.md: -------------------------------------------------------------------------------- 1 | **目标:** 2 | - 学习一组新单词,我们通过在对话中高频使用新单词,从而理解其含义和用法 -------------------------------------------------------------------------------- /images/gradio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/images/gradio.png -------------------------------------------------------------------------------- /images/gradio_0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/images/gradio_0.png -------------------------------------------------------------------------------- /images/gradio_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/images/gradio_1.png -------------------------------------------------------------------------------- /prompts/conversation_prompt.txt: -------------------------------------------------------------------------------- 1 | You are a patient and encouraging English teacher, named DjangoPeng, skilled in tailoring lessons to students of different proficiency levels (beginner, intermediate, advanced). 2 | 3 | Your task is to provide conversation-based training to help students improve their English speaking and listening skills. For each scenario listed below, design a dialogue with at least 10 turns. You will ask questions and guide the student to provide appropriate responses, correcting them when necessary and offering feedback. The conversation scenarios include: 4 | 5 | 1. **Technical Interview**: Simulate a typical technical interview covering personal introductions, technical questions, and behavioral interview questions. 6 | 2. **Restaurant Ordering**: Simulate ordering at a restaurant, including asking about the menu, placing an order, making special requests, and paying. 7 | 3. **Meeting Hosting**: Simulate hosting a meeting, including opening remarks, guiding speakers, managing time, and summarizing the meeting. 8 | 9 | **Dialogue Flow:** 10 | 1. Start by guiding the student into one of the scenarios. 11 | 2. If the student asks a general question like "I want to learn English," respond by introducing one of the conversation scenarios and explain its purpose in simple terms. 12 | - For example: "Great! Let’s start by practicing ordering food in a restaurant. Imagine you are at a restaurant and ready to order. How would you start?" 13 | 14 | 3. If the student expresses difficulty or confusion, provide a reference sentence in English and ask the student to repeat it before continuing the scenario. You can provide at least 3 reference sentences. For example: 15 | - "Could you help me with this part?" 16 | - "What do you recommend?" 17 | - "I’d like to order something vegetarian." 18 | 19 | 4. Provide feedback and guidance in Chinese, but include at least 3 reference sentences in English to help the student. For example: 20 | - 做得很好!如果你想询问推荐的菜品,可以说:'What do you recommend?' 或者 'Do you have any specials today?' 再试试用这些句子问一下吧!" 21 | 22 | Please note: 23 | - Adjust the difficulty of the conversation based on the student’s responses. 24 | - After the conversation ends, provide brief feedback, summarizing key learning points and suggesting areas for improvement. 25 | -------------------------------------------------------------------------------- /prompts/hotel_checkin_prompt.txt: -------------------------------------------------------------------------------- 1 | **System Prompt: Hotel Check-in Scenario** 2 | 3 | **Role**: 4 | You are DjangoPeng, an English teacher specializing in practical English language learning. You play the role of a hotel staff member assisting the student with the hotel check-in process while guiding their English skills. 5 | 6 | **Task**: 7 | - Simulate a realistic hotel check-in experience. 8 | - Guide the student through: 9 | 1. **Greeting and Check-in**: Handle check-in by confirming booking details, requesting identification, and assigning a room. 10 | 2. **Room Requests**: Assist with room preferences or upgrades. 11 | 3. **Facilities and Services**: Introduce the hotel's amenities. 12 | 4. **Local Recommendations**: Suggest nearby restaurants and entertainment options. 13 | 14 | - Every ChatBot response must include a **Dialogue Hint** to guide the student’s next step, with both English and Chinese examples. 15 | - **Encouragement**: Only provide encouragement when the student’s response jumps out of the current scenario. The encouragement should gently guide the student back to the context of the conversation. 16 | - After **20 rounds of conversation**, provide detailed feedback on the student’s performance, with both English and Chinese versions. 17 | 18 | **Format**: 19 | 1. **Normal Responses**: Use the format: 20 | ``` 21 | DjangoPeng: """normal response""" 22 | 23 | 对话提示: 24 | Example sentence in English 25 | Example sentence in Chinese 26 | ``` 27 | 2. **Encouragement**: Only provide encouragement when the student strays from the scenario. Guide them back by saying something positive like: "Good try! Let’s focus on the hotel check-in process." 28 | 29 | 3. **Feedback**: After 20 rounds of dialogue, provide feedback in both English and Chinese. Focus on: 30 | - **Strengths**: What the student did well. 31 | - **Improvements**: Areas for improvement. 32 | - **Encouragement**: Motivate the student to continue practicing English. 33 | 34 | Example: 35 | ``` 36 | Feedback: 37 | English: You did a great job handling the check-in process. Your sentence structure is improving, but try to use more polite expressions. Keep practicing, and you'll get even better! 38 | Chinese: 你在处理入住流程方面表现得很好。你的句子结构在进步,但可以尝试使用更多礼貌的表达方式。继续练习,你会变得更好! 39 | ``` 40 | 41 | **Examples**: 42 | - If the student says, "I want to check in": 43 | ``` 44 | DjangoPeng: Hi there! Welcome to our hotel. I'm Django, one of the front desk staff members. Can you please show me your booking confirmation or ID? We need to verify your reservation. 45 | 46 | 对话提示: 47 | Here is my booking confirmation. Can you confirm my reservation? 48 | 这是我的预订确认。你能确认我的预订吗? 49 | ``` 50 | 51 | - If the student strays from the scenario: 52 | ``` 53 | DjangoPeng: Good try! Let’s focus on the hotel check-in process. Could you show me your booking confirmation? 54 | 55 | 对话提示: 56 | Here's my passport. Do you need anything else? 57 | 这是我的护照。你还需要什么吗? 58 | ``` -------------------------------------------------------------------------------- /prompts/job_interview_prompt.txt: -------------------------------------------------------------------------------- 1 | **System Prompt: Job Interview for Internet R&D Engineer** 2 | 3 | **Role**: 4 | You are DjangoPeng, a professional interviewer at a leading internet technology company. Your job is to conduct a thorough and structured interview for the position of **Internet R&D Engineer**. You evaluate the candidate’s technical skills, problem-solving abilities, and their suitability for the role, while maintaining a professional and engaging tone throughout the interview. You will also guide the candidate in improving their communication in English as part of the interview process. 5 | 6 | **Task**: 7 | - Conduct a realistic job interview for the role of **Internet R&D Engineer**. 8 | - Treat the user as a **job candidate**, not a student. Your aim is to evaluate their qualifications and fit for the role while assisting with their English language proficiency. 9 | - Guide the candidate through: 10 | 1. **Introduction**: Ask them to introduce themselves and share their technical background. 11 | 2. **Technical Skills**: Explore their expertise in software development, programming languages, and relevant technologies (e.g., Python, Java, cloud infrastructure, microservices, DevOps). 12 | 3. **Project Experience**: Discuss their previous projects, especially those related to research and development. 13 | 4. **Innovation and Research**: Ask how they stay current with new technologies and trends in internet R&D. 14 | 5. **Company Knowledge and Motivation**: Inquire about their knowledge of the company and why they want the position of Internet R&D Engineer. 15 | 6. **Final Remarks**: Ask if they have any questions and provide closing remarks. 16 | 17 | - Every ChatBot response must include a **Dialogue Hint** to guide the candidate’s next step, with both English and Chinese examples. 18 | - **Encouragement**: Offer encouragement only when the candidate's reply jumps out of the interview scenario, gently guiding them back to the context. 19 | - After **20 rounds of conversation**, provide detailed feedback on the candidate’s performance, with both English and Chinese versions. 20 | 21 | **Format**: 22 | 1. **Normal Responses**: Use the format: 23 | ``` 24 | DjangoPeng: """normal response""" 25 | 26 | 对话提示: 27 | Example sentence in English 28 | Example sentence in Chinese 29 | ``` 30 | 2. **Feedback**: After 20 rounds, provide feedback in both English and Chinese. Focus on: 31 | - **Strengths**: Highlight where the candidate performed well. 32 | - **Improvements**: Suggest areas for improvement. 33 | - **Encouragement**: Motivate the candidate to continue improving their communication and interview skills. 34 | 35 | Example: 36 | ``` 37 | Feedback: 38 | English: You did a great job explaining your technical background. It would help if you provided more detailed examples of your R&D experience. Keep practicing, and you’ll continue to improve! 39 | Chinese: 你很好地解释了你的技术背景。你可以通过提供更多有关研发经验的详细示例来提高。继续练习,你会不断进步! 40 | ``` 41 | 42 | **Examples**: 43 | - If the candidate says, "I am here for the interview": 44 | ``` 45 | DjangoPeng: Great! Welcome to the interview for the Internet R&D Engineer position. Could you start by introducing yourself and your technical background? 46 | 47 | 对话提示: 48 | I have 5 years of experience in software development, focusing on backend development and cloud solutions. 49 | 我有五年的软件开发经验,专注于后端开发和云解决方案。 50 | ``` 51 | 52 | - If the candidate strays from the scenario: 53 | ``` 54 | DjangoPeng: That’s an interesting point! Let’s focus back on your experience as an R&D engineer. Could you tell me about a recent project where you worked on cloud infrastructure? 55 | 56 | 对话提示: 57 | In my last project, I designed and implemented a scalable backend system using AWS and Docker. 58 | 在我的上一个项目中,我使用AWS和Docker设计并实施了一个可扩展的后端系统。 59 | ``` -------------------------------------------------------------------------------- /prompts/vocab_study_prompt.txt: -------------------------------------------------------------------------------- 1 | **Role**: 2 | You are an English teacher named **DjangoPeng** who helps students accumulate vocabulary through new teaching tasks. 3 | 4 | **Task**: 5 | Facilitate vocabulary acquisition by introducing new words, engaging students in scenario-based conversations, and providing comprehensive feedback on their usage. 6 | 7 | **Format**: 8 | 9 | 1. **Introduction**: 10 | - Introduce role and task. 11 | ``` 12 | - **DjangoPeng**: "Welcome! I'm **DjangoPeng**, your Language Mentor. Today, you will learn **5 new words** as below." 13 | ``` 14 | 15 | 2. **Vocabulary Presentation**: 16 | - Present the vocabulary with the following format: 17 | 18 | ``` 19 | [No.]: [Word] 20 | - **[Chinese Meaning]**, [Part of Speech (Noun/Verb/Adjective)] 21 | - ( [Third Person Singula]; [Present Participle]; [Past Simple]; [Past Participle] ) 22 | - **[Definition]** 23 | - **例句**: [Example] 24 | ``` 25 | 26 | - **Example**: 27 | 28 | ``` 29 | 1: Innovate 30 | - **革新,创新**, Verb 31 | - 第三人称单数 innovates;现在分词 innovating;过去式 innovated;过去分词 innovated 32 | - **To make changes in something established, especially by introducing new methods, ideas, or products.** 33 | - **例句**: "Companies must innovate to stay competitive in the market." 34 | ``` 35 | 36 | 3. **Confirmation**: 37 | - Confirm we can start the conversation 38 | 39 | - **Example**: 40 | 41 | ``` 42 | ....Words... 43 | 44 | 以上就是我们今天要掌握的单词,现在让我们开始通过对话来熟练使用吧! 45 | ``` 46 | 47 | 4. **Start Simulated Conversation and Hint**: 48 | - Brief describe the scenario and our roles for the conversation to start the dialogue. 49 | 50 | ``` 51 | - **场景说明**: [Brief description] 52 | 53 | - **DjangoPeng**: [Ask a clever question to begin the dialogue]. 54 | 55 | - **提示例句**: [Hint: An example of student response using at least one of the words] 56 | ``` 57 | 58 | 5. **Multi-Round Interaction** 59 | - Engage in a back-and-forth conversation, encouraging the student to use all **words** provided. Each round should be thoughtfully designed to incorporate one or more of the new vocabulary words. 60 | 61 | ``` 62 | ...Fisrt-Round Dialogue... 63 | 64 | - **DjangoPeng**: [DjangoPeng reponse and continue the dialogue]. 65 | 66 | - **提示例句**: [Hint: An example of student response using at least one of the words] 67 | 68 | ``` 69 | 70 | 6. **Feedback**: 71 | - Once the student has used all **words** from the vocabulary list in their conversation history, provide feedback with following format: 72 | 73 | - **Comprehensive Score**: 74 | "You scored **[score]** out of **[total]**." 75 | 76 | - **Corrected Usage**: 77 | "Here are some corrections for your usage: 78 | - **[Word]**: [Correction] 79 | - **[Word]**: [Correction]" 80 | 81 | - **Native Expression**: 82 | "Here’s a more native-like way to express your thoughts: 83 | - Original: [Student's Sentence] 84 | - Native-like: [Improved Sentence]" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | langchain==0.2.16 2 | langchain_core==0.2.41 3 | langchain_community==0.2.17 4 | langchain_openai==0.1.25 5 | langchain_ollama==0.1.3 6 | gradio==4.43.0 7 | loguru==0.7.2 -------------------------------------------------------------------------------- /src/agents/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DjangoPeng/LanguageMentor/c1210d4e6cf6c6f89dba957135cb165306dbe0a9/src/agents/__init__.py -------------------------------------------------------------------------------- /src/agents/agent_base.py: -------------------------------------------------------------------------------- 1 | import json 2 | from abc import ABC, abstractmethod 3 | 4 | from langchain_ollama.chat_models import ChatOllama # 导入 ChatOllama 模型 5 | from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder # 导入提示模板相关类 6 | from langchain_core.messages import HumanMessage # 导入消息类 7 | from langchain_core.runnables.history import RunnableWithMessageHistory # 导入带有消息历史的可运行类 8 | 9 | from .session_history import get_session_history # 导入会话历史相关方法 10 | from utils.logger import LOG # 导入日志工具 11 | 12 | class AgentBase(ABC): 13 | """ 14 | 抽象基类,提供代理的共有功能。 15 | """ 16 | def __init__(self, name, prompt_file, intro_file=None, session_id=None): 17 | self.name = name 18 | self.prompt_file = prompt_file 19 | self.intro_file = intro_file 20 | self.session_id = session_id if session_id else self.name 21 | self.prompt = self.load_prompt() 22 | self.intro_messages = self.load_intro() if self.intro_file else [] 23 | self.create_chatbot() 24 | 25 | def load_prompt(self): 26 | """ 27 | 从文件加载系统提示语。 28 | """ 29 | try: 30 | with open(self.prompt_file, "r", encoding="utf-8") as file: 31 | return file.read().strip() 32 | except FileNotFoundError: 33 | raise FileNotFoundError(f"找不到提示文件 {self.prompt_file}!") 34 | 35 | def load_intro(self): 36 | """ 37 | 从 JSON 文件加载初始消息。 38 | """ 39 | try: 40 | with open(self.intro_file, "r", encoding="utf-8") as file: 41 | return json.load(file) 42 | except FileNotFoundError: 43 | raise FileNotFoundError(f"找不到初始消息文件 {self.intro_file}!") 44 | except json.JSONDecodeError: 45 | raise ValueError(f"初始消息文件 {self.intro_file} 包含无效的 JSON!") 46 | 47 | def create_chatbot(self): 48 | """ 49 | 初始化聊天机器人,包括系统提示和消息历史记录。 50 | """ 51 | # 创建聊天提示模板,包括系统提示和消息占位符 52 | system_prompt = ChatPromptTemplate.from_messages([ 53 | ("system", self.prompt), # 系统提示部分 54 | MessagesPlaceholder(variable_name="messages"), # 消息占位符 55 | ]) 56 | 57 | # 初始化 ChatOllama 模型,配置参数 58 | self.chatbot = system_prompt | ChatOllama( 59 | model="llama3.1:8b-instruct-q8_0", # 使用的模型名称 60 | max_tokens=8192, # 最大生成的 token 数 61 | temperature=0.8, # 随机性配置 62 | ) 63 | 64 | # 将聊天机器人与消息历史记录关联 65 | self.chatbot_with_history = RunnableWithMessageHistory(self.chatbot, get_session_history) 66 | 67 | def chat_with_history(self, user_input, session_id=None): 68 | """ 69 | 处理用户输入,生成包含聊天历史的回复。 70 | 71 | 参数: 72 | user_input (str): 用户输入的消息 73 | session_id (str, optional): 会话的唯一标识符 74 | 75 | 返回: 76 | str: AI 生成的回复 77 | """ 78 | if session_id is None: 79 | session_id = self.session_id 80 | 81 | response = self.chatbot_with_history.invoke( 82 | [HumanMessage(content=user_input)], # 将用户输入封装为 HumanMessage 83 | {"configurable": {"session_id": session_id}}, # 传入配置,包括会话ID 84 | ) 85 | 86 | LOG.debug(f"[ChatBot][{self.name}] {response.content}") # 记录调试日志 87 | return response.content # 返回生成的回复内容 88 | -------------------------------------------------------------------------------- /src/agents/conversation_agent.py: -------------------------------------------------------------------------------- 1 | from langchain_core.messages import AIMessage # 导入消息类 2 | 3 | from .session_history import get_session_history # 导入会话历史相关方法 4 | from .agent_base import AgentBase 5 | from utils.logger import LOG 6 | 7 | class ConversationAgent(AgentBase): 8 | """ 9 | 对话代理类,负责处理与用户的对话。 10 | """ 11 | def __init__(self, session_id=None): 12 | super().__init__( 13 | name="conversation", 14 | prompt_file="prompts/conversation_prompt.txt", 15 | session_id=session_id 16 | ) 17 | -------------------------------------------------------------------------------- /src/agents/scenario_agent.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | from langchain_core.messages import AIMessage # 导入消息类 4 | 5 | from .session_history import get_session_history # 导入会话历史相关方法 6 | from .agent_base import AgentBase 7 | from utils.logger import LOG 8 | 9 | 10 | class ScenarioAgent(AgentBase): 11 | """ 12 | 场景代理类,负责处理特定场景下的对话。 13 | """ 14 | def __init__(self, scenario_name, session_id=None): 15 | prompt_file = f"prompts/{scenario_name}_prompt.txt" 16 | intro_file = f"content/intro/{scenario_name}.json" 17 | super().__init__( 18 | name=scenario_name, 19 | prompt_file=prompt_file, 20 | intro_file=intro_file, 21 | session_id=session_id 22 | ) 23 | 24 | def start_new_session(self, session_id=None): 25 | """ 26 | 开始一个新的场景会话,并发送随机的初始 AI 消息。 27 | 28 | 参数: 29 | session_id (str, optional): 会话的唯一标识符 30 | 31 | 返回: 32 | str: 初始 AI 消息 33 | """ 34 | if session_id is None: 35 | session_id = self.session_id 36 | 37 | history = get_session_history(session_id) 38 | LOG.debug(f"[history][{session_id}]:{history}") 39 | 40 | if not history.messages: 41 | initial_ai_message = random.choice(self.intro_messages) # 随机选择初始AI消息 42 | history.add_message(AIMessage(content=initial_ai_message)) # 添加初始AI消息到历史记录 43 | return initial_ai_message 44 | else: 45 | return history.messages[-1].content # 返回历史记录中的最后一条消息 46 | -------------------------------------------------------------------------------- /src/agents/session_history.py: -------------------------------------------------------------------------------- 1 | from langchain_core.chat_history import ( 2 | BaseChatMessageHistory, # 基础聊天消息历史类 3 | InMemoryChatMessageHistory, # 内存中的聊天消息历史类 4 | ) 5 | 6 | 7 | # 用于存储会话历史的字典 8 | store = {} 9 | 10 | def get_session_history(session_id: str) -> BaseChatMessageHistory: 11 | """ 12 | 获取指定会话ID的聊天历史。如果该会话ID不存在,则创建一个新的聊天历史实例。 13 | 14 | 参数: 15 | session_id (str): 会话的唯一标识符 16 | 17 | 返回: 18 | BaseChatMessageHistory: 对应会话的聊天历史对象 19 | """ 20 | if session_id not in store: 21 | # 如果会话ID不存在于存储中,创建一个新的内存聊天历史实例 22 | store[session_id] = InMemoryChatMessageHistory() 23 | return store[session_id] -------------------------------------------------------------------------------- /src/agents/vocab_agent.py: -------------------------------------------------------------------------------- 1 | from langchain_core.messages import AIMessage # 导入 AI 消息类 2 | 3 | from .session_history import get_session_history # 导入用于处理会话历史的方法 4 | from .agent_base import AgentBase # 导入基础代理类 5 | from utils.logger import LOG # 导入日志记录模块 6 | 7 | class VocabAgent(AgentBase): 8 | """ 9 | 词汇学习代理类,负责处理与用户的对话。 10 | 继承自 AgentBase 基类。 11 | """ 12 | def __init__(self, session_id=None): 13 | # 调用父类的构造函数,初始化代理名称、提示文件路径以及可选的会话 ID 14 | super().__init__( 15 | name="vocab_study", # 定义代理的名称 16 | prompt_file="prompts/vocab_study_prompt.txt", # 提示词文件的路径 17 | session_id=session_id # 会话唯一标识符,默认为 None 18 | ) 19 | 20 | def restart_session(self, session_id=None): 21 | """ 22 | 重新启动会话,清除会话历史。 23 | 24 | 参数: 25 | session_id (str, optional): 会话的唯一标识符。如果未提供,将使用当前会话 ID。 26 | 27 | 返回: 28 | str: 返回清空后的会话历史,作为初始的 AI 消息。 29 | """ 30 | # 如果没有传递 session_id,则使用实例中的 session_id 31 | if session_id is None: 32 | session_id = self.session_id 33 | 34 | # 获取该会话的历史记录对象 35 | history = get_session_history(session_id) 36 | # 清除该会话的历史记录 37 | history.clear() 38 | # 记录清除后的会话历史到日志中 39 | LOG.debug(f"[history][{session_id}]:{history}") 40 | 41 | # 返回清空后的会话历史记录 42 | return history 43 | -------------------------------------------------------------------------------- /src/main.py: -------------------------------------------------------------------------------- 1 | import gradio as gr 2 | from tabs.scenario_tab import create_scenario_tab 3 | from tabs.conversation_tab import create_conversation_tab 4 | from tabs.vocab_tab import create_vocab_tab 5 | from utils.logger import LOG 6 | 7 | def main(): 8 | with gr.Blocks(title="LanguageMentor 英语私教") as language_mentor_app: 9 | create_scenario_tab() 10 | create_conversation_tab() 11 | create_vocab_tab() 12 | 13 | # 启动应用 14 | language_mentor_app.launch(share=True, server_name="0.0.0.0") 15 | 16 | if __name__ == "__main__": 17 | main() 18 | -------------------------------------------------------------------------------- /src/tabs/conversation_tab.py: -------------------------------------------------------------------------------- 1 | # tabs/conversation_tab.py 2 | 3 | import gradio as gr 4 | from agents.conversation_agent import ConversationAgent 5 | from utils.logger import LOG 6 | 7 | # 初始化对话代理 8 | conversation_agent = ConversationAgent() 9 | 10 | def handle_conversation(user_input, chat_history): 11 | bot_message = conversation_agent.chat_with_history(user_input) 12 | LOG.info(f"[Conversation ChatBot]: {bot_message}") 13 | return bot_message 14 | 15 | def create_conversation_tab(): 16 | with gr.Tab("对话"): 17 | gr.Markdown("## 练习英语对话 ") # 对话练习说明 18 | conversation_chatbot = gr.Chatbot( 19 | placeholder="你的英语私教 DjangoPeng

想和我聊什么话题都可以,记得用英语哦!", # 聊天机器人的占位符 20 | height=800, # 聊天窗口高度 21 | ) 22 | 23 | # 处理用户对话的函数 24 | def handle_conversation(user_input, chat_history): 25 | bot_message = conversation_agent.chat_with_history(user_input) # 获取聊天机器人的回复 26 | LOG.info(f"[ChatBot]: {bot_message}") # 记录聊天机器人的回复 27 | return bot_message # 返回机器人的回复 28 | 29 | 30 | gr.ChatInterface( 31 | fn=handle_conversation, # 处理对话的函数 32 | chatbot=conversation_chatbot, # 聊天机器人组件 33 | retry_btn=None, # 不显示重试按钮 34 | undo_btn=None, # 不显示撤销按钮 35 | clear_btn="清除历史记录", # 清除历史记录按钮文本 36 | submit_btn="发送", # 发送按钮文本 37 | ) -------------------------------------------------------------------------------- /src/tabs/scenario_tab.py: -------------------------------------------------------------------------------- 1 | # tabs/scenario_tab.py 2 | 3 | import gradio as gr 4 | from agents.scenario_agent import ScenarioAgent 5 | from utils.logger import LOG 6 | 7 | # 初始化场景代理 8 | agents = { 9 | "job_interview": ScenarioAgent("job_interview"), 10 | "hotel_checkin": ScenarioAgent("hotel_checkin"), 11 | # 可以根据需要添加更多场景代理 12 | } 13 | 14 | def get_page_desc(scenario): 15 | try: 16 | with open(f"content/page/{scenario}.md", "r", encoding="utf-8") as file: 17 | scenario_intro = file.read().strip() 18 | return scenario_intro 19 | except FileNotFoundError: 20 | LOG.error(f"场景介绍文件 content/page/{scenario}.md 未找到!") 21 | return "场景介绍文件未找到。" 22 | 23 | # 获取场景介绍并启动新会话的函数 24 | def start_new_scenario_chatbot(scenario): 25 | initial_ai_message = agents[scenario].start_new_session() # 启动新会话并获取初始AI消息 26 | 27 | return gr.Chatbot( 28 | value=[(None, initial_ai_message)], # 设置聊天机器人的初始消息 29 | height=600, # 聊天窗口高度 30 | ) 31 | 32 | # 场景代理处理函数,根据选择的场景调用相应的代理 33 | def handle_scenario(user_input, chat_history, scenario): 34 | bot_message = agents[scenario].chat_with_history(user_input) # 获取场景代理的回复 35 | LOG.info(f"[ChatBot]: {bot_message}") # 记录场景代理的回复 36 | return bot_message # 返回场景代理的回复 37 | 38 | def create_scenario_tab(): 39 | with gr.Tab("场景"): # 场景标签 40 | gr.Markdown("## 选择一个场景完成目标和挑战") # 场景选择说明 41 | 42 | # 创建单选框组件 43 | scenario_radio = gr.Radio( 44 | choices=[ 45 | ("求职面试", "job_interview"), # 求职面试选项 46 | ("酒店入住", "hotel_checkin"), # 酒店入住选项 47 | # ("薪资谈判", "salary_negotiation"), # 薪资谈判选项(注释掉) 48 | # ("租房", "renting") # 租房选项(注释掉) 49 | ], 50 | label="场景" # 单选框标签 51 | ) 52 | 53 | scenario_intro = gr.Markdown() # 场景介绍文本组件 54 | scenario_chatbot = gr.Chatbot( 55 | placeholder="你的英语私教 DjangoPeng

选择场景后开始对话吧!", # 聊天机器人的占位符 56 | height=600, # 聊天窗口高度 57 | ) 58 | 59 | # 更新场景介绍并在场景变化时启动新会话 60 | scenario_radio.change( 61 | fn=lambda s: (get_page_desc(s), start_new_scenario_chatbot(s)), # 更新场景介绍和聊天机器人 62 | inputs=scenario_radio, # 输入为选择的场景 63 | outputs=[scenario_intro, scenario_chatbot], # 输出为场景介绍和聊天机器人组件 64 | ) 65 | 66 | # 场景聊天界面 67 | gr.ChatInterface( 68 | fn=handle_scenario, # 处理场景聊天的函数 69 | chatbot=scenario_chatbot, # 聊天机器人组件 70 | additional_inputs=scenario_radio, # 额外输入为场景选择 71 | retry_btn=None, # 不显示重试按钮 72 | undo_btn=None, # 不显示撤销按钮 73 | clear_btn="清除历史记录", # 清除历史记录按钮文本 74 | submit_btn="发送", # 发送按钮文本 75 | ) 76 | -------------------------------------------------------------------------------- /src/tabs/vocab_tab.py: -------------------------------------------------------------------------------- 1 | # tabs/vocab_tab.py 2 | 3 | import gradio as gr 4 | from agents.vocab_agent import VocabAgent 5 | from utils.logger import LOG 6 | 7 | # 初始化词汇代理,负责管理词汇学习会话 8 | vocab_agent = VocabAgent() 9 | 10 | # 定义功能名称为“vocab_study”,表示词汇学习模块 11 | feature = "vocab_study" 12 | 13 | # 获取页面描述,从指定的 markdown 文件中读取介绍内容 14 | def get_page_desc(feature): 15 | try: 16 | # 打开指定的 markdown 文件来读取词汇学习介绍 17 | with open(f"content/page/{feature}.md", "r", encoding="utf-8") as file: 18 | scenario_intro = file.read().strip() # 去除多余空白 19 | return scenario_intro 20 | except FileNotFoundError: 21 | # 如果找不到文件,记录错误并返回默认消息 22 | LOG.error(f"词汇学习介绍文件 content/page/{feature}.md 未找到!") 23 | return "词汇学习介绍文件未找到。" 24 | 25 | # 重新启动词汇学习聊天机器人会话 26 | def restart_vocab_study_chatbot(): 27 | vocab_agent.restart_session() # 重启会话 28 | 29 | # 定义初始消息并与词汇代理交互生成机器人的回应 30 | _next_round = "Let's do it" 31 | bot_message = vocab_agent.chat_with_history(_next_round) 32 | 33 | # 返回一个带有初始消息和机器回复的聊天机器人界面 34 | return gr.Chatbot( 35 | value=[(_next_round, bot_message)], 36 | height=800, # 设置聊天机器人组件的高度 37 | ) 38 | 39 | # 处理用户输入的单词学习消息,并与词汇代理互动获取机器人的响应 40 | def handle_vocab(user_input, chat_history): 41 | bot_message = vocab_agent.chat_with_history(user_input) # 获取机器回复 42 | LOG.info(f"[Vocab ChatBot]: {bot_message}") # 记录机器人回应信息 43 | return bot_message 44 | 45 | # 创建词汇学习的 Tab 界面 46 | def create_vocab_tab(): 47 | # 创建一个 Tab,标题为“单词” 48 | with gr.Tab("单词"): 49 | gr.Markdown("## 闯关背单词") # 添加 Markdown 标题 50 | 51 | # 显示从文件中获取的页面描述 52 | gr.Markdown(get_page_desc(feature)) 53 | 54 | # 初始化一个聊天机器人组件,设置占位符文本和高度 55 | vocab_study_chatbot = gr.Chatbot( 56 | placeholder="你的英语私教 DjangoPeng

开始学习新单词吧!", 57 | height=800, 58 | ) 59 | 60 | # 创建一个按钮,用于重置词汇学习状态,值为“下一关” 61 | restart_btn = gr.ClearButton(value="下一关") 62 | 63 | # 当用户点击按钮时,调用 restart_vocab_study_chatbot 函数 64 | restart_btn.click( 65 | fn=restart_vocab_study_chatbot, 66 | inputs=None, 67 | outputs=vocab_study_chatbot, 68 | ) 69 | 70 | # 创建聊天接口,包含处理用户消息的函数,并关联聊天机器人组件 71 | gr.ChatInterface( 72 | fn=handle_vocab, # 处理用户输入的函数 73 | chatbot=vocab_study_chatbot, # 关联的聊天机器人组件 74 | retry_btn=None, # 不显示重试按钮 75 | undo_btn=None, # 不显示撤销按钮 76 | clear_btn=None, # 学习下一批新单词按钮 77 | submit_btn="发送", # 发送按钮的文本 78 | ) 79 | -------------------------------------------------------------------------------- /src/utils/logger.py: -------------------------------------------------------------------------------- 1 | from loguru import logger 2 | import sys 3 | import logging 4 | 5 | # 定义统一的日志格式字符串 6 | log_format = "{time:YYYY-MM-DD HH:mm:ss} | {level} | {module}:{function}:{line} - {message}" 7 | 8 | # 配置 Loguru,移除默认的日志配置 9 | logger.remove() 10 | 11 | # 使用统一的日志格式配置标准输出和标准错误输出,支持彩色显示 12 | logger.add(sys.stdout, level="DEBUG", format=log_format, colorize=True) 13 | logger.add(sys.stderr, level="ERROR", format=log_format, colorize=True) 14 | 15 | # 同样使用统一的格式配置日志文件输出,设置文件大小为1MB自动轮换 16 | logger.add("logs/app.log", rotation="1 MB", level="DEBUG", format=log_format) 17 | 18 | # 为 logger 设置别名,方便在其他模块中导入和使用 19 | LOG = logger 20 | 21 | # 将 LOG 变量公开,允许其他模块通过 from logger import LOG 来使用它 22 | __all__ = ["LOG"] 23 | -------------------------------------------------------------------------------- /src/utils/merge_requirements.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import importlib.metadata 4 | import re 5 | import os 6 | 7 | # 解析包的版本规范 8 | def parse_package_spec(spec): 9 | """ 10 | 解析包名和版本规范。 11 | 返回 (name, operator, version)。 12 | """ 13 | match = re.match(r'^([^=<>!~]+)\s*([=<>!~]+)\s*(.+)$', spec) 14 | if match: 15 | name, op, version = match.groups() 16 | return name.strip(), op.strip(), version.strip() 17 | else: 18 | return spec.strip(), None, None 19 | 20 | # 获取已安装包的版本 21 | def get_installed_versions(packages): 22 | installed_versions = {} 23 | for pkg in packages: 24 | name, _, _ = parse_package_spec(pkg) 25 | try: 26 | installed_version = importlib.metadata.version(name) 27 | installed_versions[name] = installed_version 28 | except importlib.metadata.PackageNotFoundError: 29 | print(f"包 {name} 未安装。") 30 | continue 31 | return installed_versions 32 | 33 | # 读取现有的 requirements.txt 34 | def read_requirements(file_path='requirements.txt'): 35 | req_versions = {} 36 | if os.path.exists(file_path): 37 | with open(file_path, 'r') as f: 38 | for line in f: 39 | line = line.strip() 40 | if not line or line.startswith('#'): 41 | continue 42 | name, op, version_spec = parse_package_spec(line) 43 | if op and version_spec: 44 | req_versions[name] = f"{op}{version_spec}" 45 | else: 46 | req_versions[name] = None # 未指定版本 47 | return req_versions 48 | 49 | # 合并包信息 50 | def merge_requirements(installed_versions, req_versions): 51 | merged_requirements = [] 52 | conflict_detected = False 53 | processed_packages = set() 54 | 55 | for name, installed_version in installed_versions.items(): 56 | if name in req_versions: 57 | req_version_spec = req_versions[name] 58 | if req_version_spec: 59 | # 检查版本是否匹配 60 | version_match = False 61 | # 支持多种版本操作符 62 | ops = ['==', '>=', '<=', '>', '<', '!=', '~='] 63 | for op in ops: 64 | if req_version_spec.startswith(op): 65 | req_op = op 66 | req_ver = req_version_spec[len(op):] 67 | break 68 | else: 69 | req_op = None 70 | req_ver = None 71 | 72 | if req_op == '==': 73 | if req_ver == installed_version: 74 | merged_requirements.append(f"{name}=={installed_version}") 75 | else: 76 | # 版本冲突 77 | merged_requirements.append(f"<<<<<<< HEAD") 78 | merged_requirements.append(f"{name}{req_version_spec}") 79 | merged_requirements.append(f"=======") 80 | merged_requirements.append(f"{name}=={installed_version}") 81 | merged_requirements.append(f">>>>>>> Merged version") 82 | conflict_detected = True 83 | else: 84 | # 如果 requirements.txt 中有版本规范但不是 '==' 85 | # 可以根据需要调整此逻辑 86 | # 这里假设只在 '==' 时进行严格匹配 87 | # 其他情况下认为没有冲突 88 | merged_requirements.append(f"{name}{req_version_spec}") 89 | else: 90 | # requirements.txt 未指定版本,直接覆盖为已安装版本 91 | merged_requirements.append(f"{name}=={installed_version}") 92 | processed_packages.add(name) 93 | else: 94 | # 包不在 requirements.txt 中,添加已安装版本 95 | merged_requirements.append(f"{name}=={installed_version}") 96 | processed_packages.add(name) 97 | 98 | # 添加 requirements.txt 中未处理的包 99 | for name, version_spec in req_versions.items(): 100 | if name not in processed_packages: 101 | if version_spec: 102 | merged_requirements.append(f"{name}{version_spec}") 103 | else: 104 | merged_requirements.append(f"{name}") 105 | 106 | return merged_requirements, conflict_detected 107 | 108 | def main(): 109 | # 读取现有的 requirements.txt 获取包列表 110 | req_versions = read_requirements('requirements.txt') 111 | packages = list(req_versions.keys()) 112 | 113 | # 获取已安装包的版本 114 | installed_versions = get_installed_versions(packages) 115 | 116 | # 合并包信息 117 | merged_requirements, conflict_detected = merge_requirements(installed_versions, req_versions) 118 | 119 | # 将合并结果写回 requirements.txt 120 | with open('requirements.txt', 'w') as f: 121 | for line in merged_requirements: 122 | f.write(line + '\n') 123 | 124 | if conflict_detected: 125 | print("requirements.txt 已更新,存在版本冲突。请手动解决冲突标记。") 126 | else: 127 | print("requirements.txt 已更新,无版本冲突。") 128 | 129 | if __name__ == "__main__": 130 | main() 131 | --------------------------------------------------------------------------------