Spaces:
Sleeping
Sleeping
| from openai import OpenAI | |
| def chat_stream(history: list[dict], api_key: str, system: str = "", model: str = "gpt-4o-mini", temperature: float = 0.7): | |
| """Streaming chat. Yields text chunks. history = [{"role": ..., "content": ...}]""" | |
| if not api_key or not api_key.strip().startswith("sk-"): | |
| raise ValueError("Nieprawidłowy klucz API. Klucz OpenAI powinien zaczynać się od 'sk-'.") | |
| client = OpenAI(api_key=api_key.strip()) | |
| messages = [] | |
| if system: | |
| messages.append({"role": "system", "content": system}) | |
| messages.extend(history) | |
| stream = client.chat.completions.create( | |
| model=model, | |
| messages=messages, | |
| max_tokens=1000, | |
| temperature=temperature, | |
| stream=True, | |
| ) | |
| for chunk in stream: | |
| delta = chunk.choices[0].delta.content or "" | |
| if delta: | |
| yield delta | |