Spaces:
Sleeping
Sleeping
File size: 1,962 Bytes
f80362a | 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 51 52 53 54 55 56 57 | # api_client.py
from logging_config import logger
from token_counter import count_tokens
from openai import OpenAI
import streamlit as st
# Model selection (add settings here and log)
MODEL_NAME = "gpt-4o-mini"
temperature = 0.3
logger.info(f"Selected model: {MODEL_NAME}, temperature: {temperature}")
def send_query_to_llm(messages):
"""
Send the constructed messages to the LLM and get a response.
Args:
messages (list): List of dictionaries forming the prompt for the LLM.
Returns:
str: The assistant's response or a fallback message if an error occurs.
"""
try:
# Count input tokens
token_data = count_tokens(messages, "o200k_base")
logger.info(f"Input prompt tokens: {token_data['total']}")
logger.info(f"Token breakdown (input): {token_data['by_role']}")
# Initialize OpenAI client
client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
# Send prompt to LLM
logger.info(f"Sending query to model: {MODEL_NAME}")
completion = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
temperature=temperature
)
# Extract assistant's response
assistant_response = completion.choices[0].message.content
#logger.info(f"Assistant response: {assistant_response}")
# Count output tokens
output_token_data = count_tokens([{"role": "assistant", "content": assistant_response}], "o200k_base")
logger.info(f"Assistant response output tokens: {output_token_data['total']}")
return assistant_response
except KeyError as e:
logger.error(f"Missing key in secrets or configuration: {e}")
return "Configuration error: Missing required API key or settings."
except Exception as e:
logger.error(f"Error communicating with OpenAI: {e}")
return "I'm sorry, I couldn't process your request at the moment."
|