开始使用免费开始使用

RAG 问答函数

就差最后一步了!RAG 工作流的最后一环是将检索到的文档与问答模型集成。

我们已经为您定义并提供了一个 prompt_with_context_builder() 函数。该函数会将从 Pinecone 索引中检索到的文档整合到提示中,供问答模型读取:

def prompt_with_context_builder(query, docs):
    delim = '\n\n---\n\n'
    prompt_start = 'Answer the question based on the context below.\n\nContext:\n'
    prompt_end = f'\n\nQuestion: {query}\nAnswer:'

    prompt = prompt_start + delim.join(docs) + prompt_end
    return prompt

您将实现 question_answering() 函数,为 OpenAI 的语言模型 gpt-4o-mini 提供额外的上下文与来源,以便更好地回答您的问题。

本练习是课程的一部分

使用 Pinecone 构建 AI 应用

查看课程

练习说明

  • 使用您的 API 密钥初始化 Pinecone 客户端(OpenAI 客户端已作为 client 提供)。
  • 'youtube_rag_dataset' 命名空间中检索与 query 文本最相似的 3 个文档。
  • 使用 OpenAI 的 'gpt-4o-mini' 模型,结合提供的 promptsys_prompt 生成回答。模型名称通过 chat_model 函数参数指定。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Initialize the Pinecone client
pc = Pinecone(api_key="____")
index = pc.Index('pinecone-datacamp')

query = "How to build next-level Q&A with OpenAI"

# Retrieve the top three most similar documents and their sources
documents, sources = retrieve(____, top_k=____, namespace='____', emb_model="text-embedding-3-small")

prompt_with_context = prompt_with_context_builder(query, documents)
print(prompt_with_context)

def question_answering(prompt, sources, chat_model):
    sys_prompt = "You are a helpful assistant that always answers questions."
    
    # Use OpenAI chat completions to generate a response
    res = ____(
        model=____,
        messages=[
            {"role": "system", "content": ____},
            {"role": "user", "content": ____}
        ],
        temperature=0
    )
    answer = res.choices[0].message.content.strip()
    answer += "\n\nSources:"
    for source in sources:
        answer += "\n" + source[0] + ": " + source[1]
    
    return answer

answer = question_answering(
  prompt=prompt_with_context,
  sources=sources,
  chat_model='gpt-4o-mini')
print(answer)
编辑并运行代码