LlamaIndex 學習筆記 - 產生回答

#RAG#LlamaIndex

這筆記是建構在 LlamaIndex 官方文件的 starter example, 對於其 Component Guides 範例的節錄/實作/追蹤

嘗試的原始碼在 https://github.com/unclefomotw/llamaindex-try/blob/main/src/rag_2.py


在 index.as_query_engine() 內可多加些參數去調整 LLM 如何生成回答給使用者

  • 可以挑自己要的 llm
  • retriever = self.as_retriever(**kwargs)
  • 藉由傳進去的參數,可以改變 prompt: return RetrieverQueryEngine.from_args(llm, retriever, **kwargs)
Simple diagram of the structure of llamaindex query engine
LlamaIndex RetrieverQueryEngine 的元素

挑 LLM

    synthesis_llm = OpenAI(model="gpt-4-turbo", temperature=0)
    query_engine = index.as_query_engine(
        llm=synthesis_llm,
        ...
    )

要注意模型跟 library 的版號問題

調整 prompt

    query_engine = index.as_query_engine(
        text_qa_template=MY_QA_PROMPT,  # magic kwargs defined in retriever_query_engine.py
        ...
    )

(response synthesizer 的) 不同回應模式,會用不同種 chat template。預設的 compact 模式會用 text_qa_template 跟 refine_template (前者是一個回答,後者是綜合多次回答)

預設的 text_qa_template 是這個一長串 (如果 is_chat_model 的話)

在測試的過程中有發現回答可能會是英文,所以可以調整給 ChatGPT 的 system prompt,多加一條「要以問題的語言作為回答」的規則

調整的方式詳見 https://github.com/unclefomotw/llamaindex-try/blob/main/src/rag_2.py 或官方文件