LightLLM OpenAI API test cases
| 13 | |
| 14 | |
| 15 | class LightLLMClient: |
| 16 | """LightLLM OpenAI API test cases""" |
| 17 | |
| 18 | def __init__(self, base_url: str = "http://localhost:8000", model_name: str = "your_model_name"): |
| 19 | self.base_url = base_url |
| 20 | self.model_name = model_name |
| 21 | self.headers = {"Content-Type": "application/json"} |
| 22 | self.conversation_history = [] |
| 23 | |
| 24 | def simple_chat(self, message: str, **kwargs) -> Dict[str, Any]: |
| 25 | """简单对话""" |
| 26 | data = { |
| 27 | "model": self.model_name, |
| 28 | "messages": [{"role": "user", "content": message}], |
| 29 | "temperature": kwargs.get("temperature", 0.7), |
| 30 | "max_tokens": kwargs.get("max_tokens", 1000), |
| 31 | **kwargs, |
| 32 | } |
| 33 | |
| 34 | response = requests.post(f"{self.base_url}/v1/chat/completions", headers=self.headers, json=data) |
| 35 | |
| 36 | if response.status_code == 200: |
| 37 | return response.json() |
| 38 | else: |
| 39 | raise Exception(f"API调用失败: {response.status_code} - {response.text}") |
| 40 | |
| 41 | def stream_chat(self, message: str, **kwargs): |
| 42 | data = { |
| 43 | "model": self.model_name, |
| 44 | "messages": [{"role": "user", "content": message}], |
| 45 | "stream": True, |
| 46 | "temperature": kwargs.get("temperature", 0.7), |
| 47 | "max_tokens": kwargs.get("max_tokens", 1000), |
| 48 | **kwargs, |
| 49 | } |
| 50 | |
| 51 | response = requests.post(f"{self.base_url}/v1/chat/completions", headers=self.headers, json=data, stream=True) |
| 52 | |
| 53 | if response.status_code == 200: |
| 54 | for line in response.iter_lines(): |
| 55 | if line: |
| 56 | line = line.decode("utf-8") |
| 57 | if line.startswith("data: "): |
| 58 | data_str = line[6:] |
| 59 | if data_str == "[DONE]": |
| 60 | break |
| 61 | try: |
| 62 | chunk = json.loads(data_str) |
| 63 | if chunk["choices"][0]["delta"].get("content"): |
| 64 | yield chunk["choices"][0]["delta"]["content"] |
| 65 | except json.JSONDecodeError: |
| 66 | continue |
| 67 | else: |
| 68 | raise Exception(f"API调用失败: {response.status_code} - {response.text}") |
| 69 | |
| 70 | def completions(self, prompt: str, **kwargs) -> Dict[str, Any]: |
| 71 | """文本补全""" |
| 72 | data = { |
no outgoing calls