|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import json |
| 5 | +from typing import List, Dict, Any |
| 6 | + |
| 7 | +import requests |
| 8 | +from dsp.modules.lm import LM |
| 9 | + |
| 10 | + |
| 11 | +class OpenAIChatLM(LM): |
| 12 | + """Minimal OpenAI Chat Completions adapter for dsp/dspy LM interface. |
| 13 | +
|
| 14 | + Returns a list of completion strings for a given prompt. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + model: str, |
| 20 | + api_key: str | None, |
| 21 | + temperature: float = 0.0, |
| 22 | + max_tokens: int = 400, |
| 23 | + api_base: str | None = None, |
| 24 | + ): |
| 25 | + super().__init__(model) |
| 26 | + self.provider = "openai" |
| 27 | + self.api_key = api_key or os.getenv("OPENAI_API_KEY") |
| 28 | + self.api_base = api_base or os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1") |
| 29 | + self.kwargs["temperature"] = temperature |
| 30 | + self.kwargs["max_tokens"] = max_tokens |
| 31 | + |
| 32 | + def basic_request(self, prompt: str, **kwargs) -> Dict[str, Any]: |
| 33 | + if not self.api_key: |
| 34 | + raise ValueError("OPENAI_API_KEY not set") |
| 35 | + |
| 36 | + url = f"{self.api_base}/chat/completions" |
| 37 | + payload = { |
| 38 | + "model": self.kwargs["model"], |
| 39 | + "messages": [ |
| 40 | + {"role": "system", "content": "You are a concise, direct startup advisor."}, |
| 41 | + {"role": "user", "content": prompt}, |
| 42 | + ], |
| 43 | + "temperature": kwargs.get("temperature", self.kwargs.get("temperature", 0.0)), |
| 44 | + "max_tokens": kwargs.get("max_tokens", self.kwargs.get("max_tokens", 400)), |
| 45 | + "n": kwargs.get("n", self.kwargs.get("n", 1)), |
| 46 | + } |
| 47 | + headers = {"Authorization": f"Bearer {self.api_key}", "Content-Type": "application/json"} |
| 48 | + resp = requests.post(url, headers=headers, data=json.dumps(payload), timeout=60) |
| 49 | + resp.raise_for_status() |
| 50 | + return resp.json() |
| 51 | + |
| 52 | + def __call__(self, prompt: str, only_completed: bool = True, return_sorted: bool = False, **kwargs) -> List[str]: |
| 53 | + data = self.basic_request(prompt, **kwargs) |
| 54 | + choices = data.get("choices", []) |
| 55 | + out: List[str] = [] |
| 56 | + for ch in choices: |
| 57 | + msg = ch.get("message", {}) |
| 58 | + content = msg.get("content") |
| 59 | + if content: |
| 60 | + out.append(content) |
| 61 | + if not out and "error" in data: |
| 62 | + raise RuntimeError(f"OpenAI error: {data['error']}") |
| 63 | + if not out: |
| 64 | + # Fallback to an empty string to avoid crashes |
| 65 | + out = [""] |
| 66 | + return out |
| 67 | + |
| 68 | + |
| 69 | +class OllamaLM(LM): |
| 70 | + """Minimal Ollama generate adapter for dsp/dspy LM interface. |
| 71 | +
|
| 72 | + Uses /api/generate (non-streaming) and returns a single completion string. |
| 73 | + """ |
| 74 | + |
| 75 | + def __init__( |
| 76 | + self, |
| 77 | + model: str, |
| 78 | + base_url: str = "http://localhost:11434", |
| 79 | + temperature: float = 0.0, |
| 80 | + max_tokens: int = 400, |
| 81 | + ): |
| 82 | + super().__init__(model) |
| 83 | + self.provider = "ollama" |
| 84 | + self.base_url = base_url.rstrip("/") |
| 85 | + self.kwargs["temperature"] = temperature |
| 86 | + self.kwargs["max_tokens"] = max_tokens |
| 87 | + |
| 88 | + def basic_request(self, prompt: str, **kwargs) -> Dict[str, Any]: |
| 89 | + url = f"{self.base_url}/api/generate" |
| 90 | + payload = { |
| 91 | + "model": self.kwargs["model"], |
| 92 | + "prompt": prompt, |
| 93 | + "stream": False, |
| 94 | + "options": { |
| 95 | + "temperature": kwargs.get("temperature", self.kwargs.get("temperature", 0.0)), |
| 96 | + "num_predict": kwargs.get("max_tokens", self.kwargs.get("max_tokens", 400)), |
| 97 | + }, |
| 98 | + } |
| 99 | + resp = requests.post(url, json=payload, timeout=120) |
| 100 | + resp.raise_for_status() |
| 101 | + return resp.json() |
| 102 | + |
| 103 | + def __call__(self, prompt: str, only_completed: bool = True, return_sorted: bool = False, **kwargs) -> List[str]: |
| 104 | + data = self.basic_request(prompt, **kwargs) |
| 105 | + text = data.get("response", "") |
| 106 | + return [text] |
0 commit comments