LLaMA 3.2 建置與測試與Prompt
LLaMA 3.2 建置與測試與Prompt¶
首先拜訪https://github.com/ollama/ollama的README文件,依據指引跟使用環境去安裝ollama
安裝後,在你的作業環境輸入
ollama pull llama3.2 # 把model載下來
接下來安裝langchain_ollama 可以去連接llama 3.2 以及streamlit讓我們可以有個簡易UI
pip install langchain_ollamapip install streamlit
接下來我們可以寫主程式,參考自LINK
import streamlit as stfrom langchain_ollama.llms import OllamaLLMfrom langchain_core.prompts import ChatPromptTemplate# 設定頁面標題st.markdown( "<h2 style='text-align: center; color: #4CAF50; font-family: Arial;'>Dan's AI assistant🪶</h2>", unsafe_allow_html=True,)# 在prompt間給予提示微調model回復CHAT_PROMPT_TEMPLATE= """You're a AI agient help customer answer questionCustomer: {question}Assistant: """prompt = ChatPromptTemplate.from_template(CHAT_PROMPT_TEMPLATE)#設定model為llama3.2model = OllamaLLM(model="llama3.2")chain = prompt | model#如果程式剛跑,沒有任何messages的情況下,先給予提示if "messages" not in st.session_state: st.session_state.messages = [ {"role": "assistant", "content": "Hi! How may I help you?"} ]#讓對話紀錄顯示在UIfor message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # 處理的使用者input跟回復,如果使用者輸入文字發送後觸發if user_input := st.chat_input("What is up?"): # 新增使用者輸入訊息到messages st.session_state.messages.append({"role": "user", "content": user_input}) # 顯示input with st.chat_message("user"): st.markdown(user_input) # 把使用者輸入給到model,拿到回復後顯示 with st.chat_message("assistant"): response = chain.invoke({"question": user_input}) st.markdown(response) # 新增回復訊息到messages st.session_state.messages.append({"role": "assistant", "content": response})
運行後應該會看到類似以下,"Hi! How may I help you?" 是最一開始設定的文字招呼
接下來探討Prompt,當一個LLM訓練完畢,他會保有大眾化的知識,因此我們可以問他很大眾化的問題,例如哪邊可以找到氣象資訊
但無法問她特定日的天氣,因為當初訓練的資料裡,不會有未來還沒發生的資料
這時候,如果我們給予點提示,例如
CHAT_PROMPT_TEMPLATE= """You're a weather AI agient help customer answer questionYou had some information about some days weatherWeather information:2025/01/11: Sunny2025/01/10: Cloudy2025/01/09: RainyCustomer: {question}Assistant: """
在詢問特定日期的天氣,發現LLM可以基於它有的資訊回答了
因此我們拿取自我介紹當作預先知識給AI agent,並且限制他的身分,如此一來,可以觀察到agent會嘗試婉拒不相關的提問並且讓回答回到他想要的方向。
CHAT_PROMPT_TEMPLATE = """As a headhunter, you've collect information about your candidate and ready introduce to your boss. Your boss will ask you question about the candidate.You will provide responses to questions related to the candidate and politely avoid answering unrelated questions.Candidate information below:---Start---<!--Candidate information here-->---End---Boss: {question}Assistant: """
以上介紹如何透過LLM跟Prompt去影響回答跟實作。
每次都透過Prompt的方式來讓AI agent適應有點繁瑣跟沒效率,因此新技術例如RAG 檢索增強生成,讓語言模型可以像學生在考試時open book看答案,或是fine tune model讓agent 變成專門回答這類題目,未來再陸續實作。
Comments
Loading comments…
Leave a Comment