File size: 873 Bytes
1e81d21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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