-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathllm_chat.py
50 lines (39 loc) · 1.47 KB
/
llm_chat.py
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import os
from typing import Literal
from dotenv import load_dotenv
from openai import OpenAI
from pydantic import BaseModel
from restack_ai.function import NonRetryableError, function, log
load_dotenv()
class Message(BaseModel):
role: Literal["system", "user", "assistant"]
content: str
class LlmChatInput(BaseModel):
system_content: str | None = None
model: str | None = None
messages: list[Message] | None = None
@function.defn()
async def llm_chat(agent_input: LlmChatInput) -> dict[str, str]:
try:
log.info("llm_chat function started", agent_input=agent_input)
if os.environ.get("RESTACK_API_KEY") is None:
raise NonRetryableError("RESTACK_API_KEY is not set")
client = OpenAI(
base_url="https://ai.restack.io", api_key=os.environ.get("RESTACK_API_KEY")
)
if agent_input.system_content:
agent_input.messages.append(
{"role": "system", "content": agent_input.system_content}
)
assistant_raw_response = client.chat.completions.create(
model=agent_input.model or "gpt-4o-mini",
messages=agent_input.messages,
)
assistant_response = {
"role": assistant_raw_response.choices[0].message.role,
"content": assistant_raw_response.choices[0].message.content,
}
except Exception as e:
raise NonRetryableError(f"LLM chat failed: {e}") from e
else:
return assistant_response