前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LLM】智能学生顾问构建技术介绍(基于Lyrz SDK + OpenAI Api 实现)

【LLM】智能学生顾问构建技术介绍(基于Lyrz SDK + OpenAI Api 实现)

原创
作者头像
Freedom123
发布2024-05-14 18:58:53
910
发布2024-05-14 18:58:53
举报
文章被收录于专栏:AIGCAIGC

toc


如果您是一名学生,你正在寻求个性化顾问来帮助你的课程作业,那么AI学生顾问正好可以帮助你,这是一种创新的解决方案,利用 AI 的力量彻底改变学生咨询。

Lyzr Student Advisor 应用程序的核心是为了让学生在学术之旅中发挥作用,通过利用 Lyzr 聊天机器人的功能,该应用程序提供量身定制的见解和建议,以帮助学生在课程作业中脱颖而出、发展职业轨迹并促进个人成长。使用 Lyzr SDK,制作您自己的 GenAI 应用程序变得轻而易举,只需几行代码即可快速启动和运行。

查看Lyzr SDK: https://docs.lyzr.ai/homepage

创建文件 app.py ,导入依赖库:

代码语言:shell
复制
import os
import shutil
import streamlit as st
from lyzr import ChatBot

该代码首先导入用于文件处理的基本模块,例如 os 和 shutil,以及用于创建 Web 应用程序(如 streamlit)。此外,从 lyzr 模块导入 ChatBot 类,这表明聊天机器人功能的潜在集成可能利用自然语言处理功能。

使用 Streamlit 的密钥管理工具初始化 OpenAI API 密钥,通过访问安全存储在 Streamlit 密钥中的特定密钥(其中安全存储了 OpenAI API 密钥),它取代了占位符“OPENAI_API_KEY”,确保了对 Streamlit 应用程序中 OpenAI API 的安全访问。

代码语言:shell
复制
# Set the OpenAI API key
os.environ["OPENAI_API_KEY"] = st.secrets["apikey"]
代码语言:shell
复制
# Function to remove existing files
def remove_existing_files(directory):
    for filename in os.listdir(directory):
        file_path = os.path.join(directory, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            st.error(f"Error while removing existing files: {e}")

函数 remove_existing_files(directory) 用于擦除指定目录中的所有文件和目录。它使用 os.listdir(directory) 遍历指定目录中的每个项目。对于遇到的每个项目,它通过将目录路径与项目的文件名组合在一起来形成完整的文件路径。随后,它尝试使用 os.unlink() 来消除文件或 shutil.rmtree() 来消除目录的项目。如果在此删除过程中出现任何错误,它会处理它们并使用 Streamlit 的 st.error() 函数显示错误通知。

代码语言:shell
复制
# Set the local directory
data_directory = "data"

# Create the data directory if it doesn't exist
os.makedirs(data_directory, exist_ok=True)

# Remove existing files in the data directory
remove_existing_files(data_directory)

这些代码行处理文件系统中名为“data”的本地目录。首先,将变量 data_directory 设置为字符串 “data”,指示要管理的目录的名称。然后,代码使用 os.makedirs(data_directory, exist_ok=True) 创建“data”目录。

exist_ok=True 参数可确保仅当目录尚不存在时才创建该目录。在此之后,调用函数 remove_existing_files(data_directory) 以清除“data”目录中任何预先存在的文件或子目录,确保它是空的并准备好使用。

代码语言:shell
复制
# Function to implement RAG Lyzr Chatbot
def rag_implementation(file_path):
    # Check the file extension
    _, file_extension = os.path.splitext(file_path)

    if file_extension.lower() == ".pdf":
        # Initialize the PDF Lyzr ChatBot
        rag = ChatBot.pdf_chat(
            input_files=[file_path],
            llm_params={"model": "gpt-4"},
        )
    elif file_extension.lower() == ".docx":
        # Initialize the DOCX Lyzr ChatBot
        rag = ChatBot.docx_chat(
            input_files=[file_path],
            llm_params={"model": "gpt-4"},
        )
    else:
        # Handle unsupported file types
        raise ValueError("Unsupported file type. Only PDF and DOCX files are supported.")

    return rag

rag_implementation,此函数用于根据提供的文件类型实现 RAG Lyzr 聊天机器人。它首先从给定file_path中提取文件扩展名。如果文件是 PDF,则使用 ChatBot 类中的 pdf_chat 方法初始化专为 PDF 文件设计的 Lyzr ChatBot。同样,如果文件是 DOCX 文档,则使用 docx_chat 方法初始化 DOCX 文件的 ChatBot。

这两个初始化过程都包括指定输入文件和设置语言模型参数,此处定义为 {“model”: “gpt-4”}。如果文件扩展名与“.pdf”或“.docx”不匹配,则该函数将引发 ValueError,指示仅支持 PDF 和 DOCX 文件。

代码语言:shell
复制
# Function to get Lyzr response
def advisor_response(file_path, ambition):
    rag = rag_implementation(file_path)
    prompt = f"""Your name is Isha, always remember that, and you are a student advisor at a university. Always introduce yourself.

                 To generate advice for the uploaded document, please follow the instructions below:

                      - Course work and grades: Being a Student Advisor, look into the uploaded marksheet and give important insights about where the student performance lies.

                      - Ambition: Informed by the student's ambition (replace {ambition}), advise them on the steps required to excel in their chosen path.

                      - Academic advice: Being a Student Advisor, look into the uploaded document and give important insights about where the student's strength and weaknesses lie and how to improve them.

                      - Career guidance: Being a student Advisor utilize the student's ambition, coursework, and grades, offer pertinent suggestions for their career trajectory.

                      - Personal development: Being a student Advisor offer guidance on fostering high productivity through effective time management techniques and engaging in relevant extracurricular activities.

                      - Please ensure adherence to these steps and provide responses akin to a student advisor. """

    response = rag.chat(prompt)
    return response.response

此advisor_response函数利用 rag_implementation 函数初始化 Lyzr ChatBot。然后,它会生成一个提示,其中包含有关建议各个方面的说明和占位符,例如课程作业、抱负、学术建议、职业指导和个人发展。占位符 {ambition} 用于将学生的抱负动态地合并到提示中。

该函数会向 Lyzr ChatBot 提示此消息,指示它根据上传的文档和提供的提示提供建议。ChatBot 处理提示并生成响应,然后由函数返回。该回复预计将包含针对学生的学术旅程和抱负量身定制的建议和见解。

代码语言:shell
复制
# File upload widget
uploaded_file = st.file_uploader("Upload your Marksheet⬇️", type=["pdf", "docx"])

if uploaded_file is not None:
    # Save the uploaded file to the data directory
    file_path = os.path.join(data_directory, uploaded_file.name)
    with open(file_path, "wb") as file:
        file.write(uploaded_file.getvalue())

    # Display the path of the stored file
    st.success("File successfully saved")

    # User input for student's ambition
    ambition = st.text_input("What is your Ambition?")

    # Generate advice button
    if st.button("Get Advice"):
        if not ambition:
            st.warning("Please enter your ambition.")
        else:
            automatic_response = advisor_response(file_path, ambition)
            st.markdown(automatic_response)

本部分代码使用 Streamlit 的 file_uploader 函数创建文件上传小部件。系统会提示用户上传其标记表文件,支持的文件类型仅限于 PDF 和 DOCX 格式。

文件上传后,代码将上传的文件保存到指定的data_directory,确保将其存储在本地以供进一步处理。将显示一条成功消息,以确认文件已成功保存。

接下来,系统会提示用户通过文本输入字段输入他们的想法。这些信息对于生成针对用户职业抱负量身定制的个性化建议至关重要。

最后,标有“获取建议”的按钮允许用户触发建议生成过程。在继续操作之前,代码会检查目标字段是否为空,并在必要时提示用户输入其目标。如果提供了 ambition,则调用 advisor_response 函数,并将path和 ambition 作为参数。然后使用 Streamlit 的 Markdown 函数向用户显示生成的建议。

以上就是基于Lyzr SDK实现的学生顾问的核心内容,希望对同学们有所帮助。

小编是一名热爱人工智能的专栏作者,致力于分享人工智能领域的最新知识、技术和趋势。这里,你将能够了解到人工智能的最新应用和创新,探讨人工智能对未来社会的影响,以及探索人工智能背后的科学原理和技术实现。欢迎大家点赞,评论,收藏,让我们一起探索人工智能的奥秘,共同见证科技的进步!

我正在参与2024腾讯技术创作特训营最新征文,快来和我瓜分大奖!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云顾问
云顾问(Tencent Cloud Smart Advisor)是一款提供可视化云架构IDE和多个ITOM领域垂直应用的云上治理平台,以“一个平台,多个应用”为产品理念,依托腾讯云海量运维专家经验,助您打造卓越架构,实现便捷、灵活的一站式云上治理。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档