provider.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """LLM provider — thin wrapper around the OpenAI SDK."""
  2. from __future__ import annotations
  3. import json
  4. from dataclasses import dataclass, field
  5. from typing import Any
  6. from openai import AsyncOpenAI
  7. @dataclass
  8. class ToolCallRequest:
  9. """A single tool-call request from the LLM."""
  10. id: str
  11. name: str
  12. arguments: dict[str, Any]
  13. @dataclass
  14. class LLMResponse:
  15. """Normalised response from an LLM provider."""
  16. content: str | None = None
  17. tool_calls: list[ToolCallRequest] = field(default_factory=list)
  18. finish_reason: str = "stop"
  19. @property
  20. def has_tool_calls(self) -> bool:
  21. return len(self.tool_calls) > 0
  22. class OpenAIProvider:
  23. """OpenAI-compatible chat-completion provider.
  24. Works with any endpoint that speaks the OpenAI API format
  25. (OpenRouter, DeepSeek, local vLLM, etc.).
  26. """
  27. def __init__(
  28. self,
  29. api_key: str,
  30. api_base: str = "https://api.openai.com/v1",
  31. default_model: str = "gpt-4o",
  32. ):
  33. self.default_model = default_model
  34. self._client = AsyncOpenAI(api_key=api_key, base_url=api_base)
  35. async def chat(
  36. self,
  37. messages: list[dict[str, Any]],
  38. tools: list[dict[str, Any]] | None = None,
  39. model: str | None = None,
  40. temperature: float = 0.1,
  41. max_tokens: int = 4096,
  42. ) -> LLMResponse:
  43. """Send a chat-completion request and return a normalised response."""
  44. kwargs: dict[str, Any] = {
  45. "model": model or self.default_model,
  46. "messages": messages,
  47. "temperature": temperature,
  48. "max_tokens": max_tokens,
  49. }
  50. if tools:
  51. kwargs["tools"] = tools
  52. kwargs["tool_choice"] = "auto"
  53. try:
  54. resp = await self._client.chat.completions.create(**kwargs)
  55. return self._parse(resp)
  56. except Exception as exc:
  57. return LLMResponse(content=f"Error calling LLM: {exc}", finish_reason="error")
  58. # ------------------------------------------------------------------
  59. # Internals
  60. # ------------------------------------------------------------------
  61. @staticmethod
  62. def _parse(resp: Any) -> LLMResponse:
  63. choice = resp.choices[0]
  64. msg = choice.message
  65. tool_calls: list[ToolCallRequest] = []
  66. if msg.tool_calls:
  67. for tc in msg.tool_calls:
  68. args = tc.function.arguments
  69. if isinstance(args, str):
  70. try:
  71. args = json.loads(args)
  72. except json.JSONDecodeError:
  73. args = {}
  74. tool_calls.append(
  75. ToolCallRequest(id=tc.id, name=tc.function.name, arguments=args)
  76. )
  77. return LLMResponse(
  78. content=msg.content,
  79. tool_calls=tool_calls,
  80. finish_reason=choice.finish_reason or "stop",
  81. )