Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

retrieve.py 1.6 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  1. import os
  2. from langchain.prompts import ChatPromptTemplate
  3. from langchain.schema import HumanMessage
  4. from langchain_community.vectorstores import Chroma
  5. from langchain_openai import ChatOpenAI, OpenAIEmbeddings
  6. OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
  7. CHROMA_PATH = "db"
  8. # Initialize embeddings and load the Chroma database
  9. embeddings = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)
  10. db_chroma = Chroma(persist_directory=CHROMA_PATH, embedding_function=embeddings)
  11. # Prompt template for generating answers
  12. PROMPT_TEMPLATE = """
  13. Answer the question based only on the following context:
  14. {context}
  15. Answer the question based on the above context: {question}.
  16. Provide a detailed answer.
  17. Don't justify your answers.
  18. Don't give information not mentioned in the CONTEXT INFORMATION.
  19. Do not say "according to the context" or "mentioned in the context" or similar.
  20. """
  21. def call_api(prompt, options, context):
  22. k = options.get("config", {}).get("topK", 5)
  23. docs_chroma = db_chroma.similarity_search_with_score(prompt, k=k)
  24. context_text = "\n\n".join([doc.page_content for doc, _score in docs_chroma])
  25. # Generate prompt using the template
  26. prompt_template = ChatPromptTemplate.from_template(PROMPT_TEMPLATE)
  27. final_prompt = prompt_template.format(context=context_text, question=prompt)
  28. # Fetch from OpenAI API
  29. chat = ChatOpenAI(
  30. model_name="gpt-4o-mini", temperature=0, openai_api_key=OPENAI_API_KEY
  31. )
  32. message = HumanMessage(content=final_prompt)
  33. response = chat([message])
  34. result = {
  35. "output": response.content,
  36. }
  37. return result
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...