Spaces:
Runtime error
Runtime error
Create mongo_db_writer_main.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from pymongo import MongoClientfrom datetime import datetimeimport json
# MongoDB ConfigurationMONGO_URI = "mongodb://96.228.37.139:27017"DATABASE_NAME = "ollama_logs"COLLECTION_NAME = "interactions"
# Initialize MongoDB Client and Collectionclient = MongoClient(MONGO_URI)db = client[DATABASE_NAME]collection = db[COLLECTION_NAME]
# Initialize MongoDB Client and Collectionclient = MongoClient(MONGO_URI)db = client[DATABASE_NAME]collection = db[COLLECTION_NAME]
def log_prompt_and_response(prompt: str, response): """ Logs the prompt and response to MongoDB and a log file. """ try: # If the response is a string, try to parse it as JSON if isinstance(response, str): try: response_data = json.loads(response) # Parse the string into a dictionary except json.JSONDecodeError: response_data = {"response": response} # If parsing fails, treat the entire string as the response else: response_data = response # Assume it's already a dictionary or JSON-serializable
# Extract the "response" field from the response_data response_text = response_data.get("response", "No response found")
# Create the log entry with only prompt and response log_entry = { "timestamp": datetime.utcnow().isoformat(), "prompt": prompt, "response": response_text, # Only store the "response" field }
# Log to MongoDB result = collection.insert_one(log_entry) # Insert into MongoDB print("Logged to MongoDB successfully!")
# Add the MongoDB _id to the log entry for reference log_entry["_id"] = str(result.inserted_id) # Convert ObjectId to string
# Log to a file with open("ollama_interactions.log", "a") as f: f.write(json.dumps(log_entry, indent=4) + "\n") print("Logged to file successfully!")
except Exception as e: print(f"Error logging prompt and response: {e}")mongo_db_writer_main.pyAdded+58