Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NonRetryableError best practice review #209

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 4 additions & 19 deletions agent_chat/src/functions/llm_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,22 @@

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


def raise_exception(message: str) -> None:
log.error(message)
raise NonRetryableError(message)


@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:
error_message = "RESTACK_API_KEY is not set"
raise_exception(error_message)
raise NonRetryableError("RESTACK_API_KEY is not set")

client = OpenAI(
base_url="https://ai.restack.io", api_key=os.environ.get("RESTACK_API_KEY")
Expand All @@ -47,19 +38,13 @@ async def llm_chat(agent_input: LlmChatInput) -> dict[str, str]:
model=agent_input.model or "gpt-4o-mini",
messages=agent_input.messages,
)
except Exception as e:
error_message = f"LLM chat failed: {e}"
raise NonRetryableError(error_message) from e
else:
log.info(
"llm_chat function completed", assistant_raw_response=assistant_raw_response
)

assistant_response = {
"role": assistant_raw_response.choices[0].message.role,
"content": assistant_raw_response.choices[0].message.content,
}

log.info("assistant_response", assistant_response=assistant_response)

except Exception as e:
raise NonRetryableError(f"LLM chat failed: {e}") from e
else:
return assistant_response