Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

tavily_conn.py 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. max_results=6
  29. )
  30. return [{"url": res["url"], "title": res["title"], "content": res["content"], "score": res["score"]} for res in response["results"]]
  31. except Exception as e:
  32. logging.exception(e)
  33. return []
  34. def retrieve_chunks(self, question):
  35. chunks = []
  36. aggs = []
  37. logging.info("[Tavily]Q: " + question)
  38. for r in self.search(question):
  39. id = get_uuid()
  40. chunks.append({
  41. "chunk_id": id,
  42. "content_ltks": rag_tokenizer.tokenize(r["content"]),
  43. "content_with_weight": r["content"],
  44. "doc_id": id,
  45. "docnm_kwd": r["title"],
  46. "kb_id": [],
  47. "important_kwd": [],
  48. "image_id": "",
  49. "similarity": r["score"],
  50. "vector_similarity": 1.,
  51. "term_similarity": 0,
  52. "vector": [],
  53. "positions": [],
  54. "url": r["url"]
  55. })
  56. aggs.append({
  57. "doc_name": r["title"],
  58. "doc_id": id,
  59. "count": 1,
  60. "url": r["url"]
  61. })
  62. logging.info("[Tavily]R: "+r["content"][:128]+"...")
  63. return {"chunks": chunks, "doc_aggs": aggs}