Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

tavily_conn.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. from tavily import TavilyClient
  18. from api.utils import get_uuid
  19. from rag.nlp import rag_tokenizer
  20. class Tavily:
  21. def __init__(self, api_key: str):
  22. self.tavily_client = TavilyClient(api_key=api_key)
  23. def search(self, query):
  24. try:
  25. response = self.tavily_client.search(
  26. query=query,
  27. search_depth="advanced"
  28. )
  29. return [{"url": res["url"], "title": res["title"], "content": res["content"], "score": res["score"]} for res in response["results"]]
  30. except Exception as e:
  31. logging.exception(e)
  32. return []
  33. def retrieve_chunks(self, question):
  34. chunks = []
  35. aggs = []
  36. logging.info("[Tavily]Q: " + question)
  37. for r in self.search(question):
  38. id = get_uuid()
  39. chunks.append({
  40. "chunk_id": id,
  41. "content_ltks": rag_tokenizer.tokenize(r["content"]),
  42. "content_with_weight": r["content"],
  43. "doc_id": id,
  44. "docnm_kwd": r["title"],
  45. "kb_id": [],
  46. "important_kwd": [],
  47. "image_id": "",
  48. "similarity": r["score"],
  49. "vector_similarity": 1.,
  50. "term_similarity": 0,
  51. "vector": [],
  52. "positions": [],
  53. "url": r["url"]
  54. })
  55. aggs.append({
  56. "doc_name": r["title"],
  57. "doc_id": id,
  58. "count": 1,
  59. "url": r["url"]
  60. })
  61. logging.info("[Tavily]R: "+r["content"][:128]+"...")
  62. return {"chunks": chunks, "doc_aggs": aggs}