File size: 1,128 Bytes
52279a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
28
29
30
31
32
33
"""OpenAI client - chat, embeddings, assistants, tools."""
import os
import requests

BASE = os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1")
KEY = os.getenv("OPENAI_API_KEY")


def _h():
    if not KEY:
        raise RuntimeError("OPENAI_API_KEY not set")
    return {"Authorization": f"Bearer {KEY}"}


def chat(messages, model="gpt-4o", stream=False, tools=None, **kwargs):
    body = {"model": model, "messages": messages, "stream": stream}
    if tools:
        body["tools"] = tools
    body.update(kwargs)
    return requests.post(f"{BASE}/chat/completions", headers=_h(), json=body, timeout=120, stream=stream)


def embeddings(inputs, model="text-embedding-3-small"):
    return requests.post(f"{BASE}/embeddings", headers=_h(), json={"model": model, "input": inputs}, timeout=120).json()


def create_assistant(**kwargs):
    return requests.post(f"{BASE}/assistants", headers=_h(), json=kwargs, timeout=60).json()


def create_run(thread_id, assistant_id, **kwargs):
    return requests.post(f"{BASE}/threads/{thread_id}/runs", headers=_h(), json={"assistant_id": assistant_id, **kwargs}, timeout=60).json()