answerQuestions.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import pandas as pd
  2. import chromadb
  3. import os
  4. import erniebot
  5. # 需要设置token
  6. erniebot.api_type = "aistudio"
  7. erniebot.access_token = ""
  8. chroma_client = chromadb.PersistentClient(path="data/chroma")
  9. vectordb = chroma_client.get_collection(name="collection")
  10. def generateStory(question):
  11. query = [
  12. question,
  13. ]
  14. response = erniebot.Embedding.create(
  15. input=query,
  16. model="ernie-text-embedding",
  17. )
  18. query_embeddings = response.data[0]["embedding"]
  19. print(query_embeddings)
  20. results = vectordb.query(query_embeddings=query_embeddings, n_results=1) # top_k
  21. search_result = {
  22. "metadatas": results["metadatas"][0],
  23. "documents": results["documents"][0],
  24. }
  25. prompt = f"你是一个擅长给小朋友讲故事的小助手,请根据自己的知识和检索到的内容,对小朋友的疑问进行解答。注意,由于小朋友的年龄较小,问题解答需要用故事的形式。尽量使故事生动、有趣、富有哲理。 \n 用户问题: {question} \n\n 搜索结果:\n {search_result}"
  26. print(prompt)
  27. messages = [{"role": "user", "content": prompt}]
  28. response = erniebot.ChatCompletion.create(model="ernie-4.0", messages=messages)
  29. story = response.get_result()
  30. return story
  31. if __name__ == "__main__":
  32. question = "什么是克隆羊"
  33. print(generateStory(question))