llm_client.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # @description:
  2. # @author: licanglong
  3. # @date: 2026/1/5 9:47
  4. import json
  5. import openai
  6. from openai.types.chat import ChatCompletion
  7. from app.core import CTX, BizException
  8. from app.utils import ali_search_tool, get_current_time
  9. class LLMClient:
  10. def get_llm_provider(self):
  11. pass
  12. def generate(self) -> str:
  13. pass
  14. async def llm_call(tools, messages):
  15. client = openai.AsyncOpenAI(
  16. api_key=CTX.ENV.getprop("llm.qwen.api_key", raise_error=True),
  17. base_url=CTX.ENV.getprop("llm.qwen.base_url", raise_error=True),
  18. )
  19. completion: ChatCompletion = await client.chat.completions.create(
  20. model="qwen-plus-latest",
  21. messages=messages,
  22. tools=tools if tools else None,
  23. tool_choice="auto" if tools else "none",
  24. # extra_body={
  25. # "enable_thinking": True
  26. # }
  27. )
  28. if not completion.choices:
  29. raise BizException("LLM响应异常")
  30. if completion.choices[0].finish_reason == "tool_calls":
  31. tool_infos = []
  32. tool_calls = completion.choices[0].message.tool_calls
  33. for call in tool_calls:
  34. if call.function.name == "ali_search_tool":
  35. args = json.loads(call.function.arguments)
  36. keyword = args["keyword"]
  37. info = await ali_search_tool(keyword)
  38. info['pageItems'] = info['pageItems'][:(min(5, len(info['pageItems'])))]
  39. tool_infos.append({
  40. "role": "tool",
  41. "tool_call_id": call.id,
  42. "content": json.dumps(info, ensure_ascii=False)
  43. })
  44. elif call.function.name == "get_current_time":
  45. info = get_current_time()
  46. tool_infos.append({
  47. "role": "tool",
  48. "tool_call_id": call.id,
  49. "content": info
  50. })
  51. return await llm_call(tools, [*messages, completion.choices[0].message, *tool_infos])
  52. generate_content = completion.choices[0].message.content
  53. return generate_content