Certainly! I'd be happy to help you with your script. It appears that you've created a Python script that:
- Accepts user input (e.g., "write a doc about pizza").
- Uses a language model to extract the title and content from the user's request.
- Creates a Google Docs document with the extracted title and content.
I'll provide a detailed review of your script, point out any potential issues, and suggest improvements to make it more efficient and reliable.
Overview of Your Script
Your script performs the following main tasks:
- Authentication: Uses OAuth 2.0 to authenticate with the Google Docs API.
- Language Model Processing: Utilizes a Hugging Face transformer model to parse the user's input and extract structured data.
- Google Docs Interaction: Creates and writes content to a Google Docs document based on the extracted data.
- User Interaction Loop: Continuously prompts the user for input until the user types "exit".
Detailed Review and Suggestions
1. Authentication with Google Docs API
Current Implementation:
SCOPES = ['https://www.googleapis.com/auth/documents']
...
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
...
docs_service = build('docs', 'v1', credentials=creds)
Suggestions:
-
Credentials Handling: Ensure that credentials.json is secured and not included in version control systems like GitHub.
-
Token Storage: To avoid re-authenticating every time the script runs, consider implementing token storage using token.json.
from google.oauth2.credentials import Credentials
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
else:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
-
Error Handling: Catch and handle specific exceptions related to authentication, such as RefreshError from the google.auth.exceptions module.
2. Loading the Hugging Face Model
Current Implementation:
model_name = "meta-llama/Llama-3.2-1B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=True)
model = AutoModelForCausalLM.from_pretrained(model_name, use_auth_token=True)
Suggestions:
-
Model Availability: As of my knowledge cutoff in September 2021, meta-llama/Llama-3.2-1B-Instruct is not an available model. Ensure that the model name is correct and that you have access rights.
Consider using a model like facebook/opt-1.3b or gpt2.
-
Model Size and Performance: Large models can be slow and consume significant memory. For quick tasks, a smaller model might suffice.
-
Authentication Token: The use_auth_token parameter requires a Hugging Face authentication token. Ensure that you've set it up correctly and securely.
-
Runtime Errors: If the model doesn't exist or you lack access, the script will raise an error. Include error handling to alert the user appropriately.
3. Parsing User Input with the Language Model
Current Implementation:
def parse_input_with_llm(model, tokenizer, user_input):
# Prepare the prompt for the LLM
prompt = f"""Extract the document title and content from the following request and return only the JSON object in the format {{"title": "TITLE", "content": "CONTENT"}} without any additional text or explanations. Do not include any code blocks or comments.
User request: "{user_input}"
JSON output:
"""
Suggestions:
-
Prompt Engineering: Be explicit in your prompt to guide the model effectively. Since models can sometimes generate additional text, reinforce that only the JSON object should be returned.
-
Output Parsing: Instead of using regex to extract JSON, consider using the json module to parse the text safely. However, since the model may produce malformed JSON, your current method is reasonable. Still, add more checks to handle edge cases.
-
Error Handling: If JSON parsing fails, provide a user-friendly message and perhaps rephrase the prompt for better results.
4. Creating and Writing to Google Docs
Current Implementation:
def create_and_write_doc(service, title, content):
# Create a new document
doc = {'title': title}
created_doc = service.documents().create(body=doc).execute()
document_id = created_doc.get('documentId')
# Insert text into the document
requests = [{
'insertText': {
'location': {'index': 1},
'text': content
}
}]
service.documents().batchUpdate(
documentId=document_id,
body={'requests': requests}
).execute()
Suggestions:
-
Input Sanitization: Ensure that the title and content variables are sanitized to prevent injection attacks or formatting issues.
-
Error Handling: Wrap API calls in try-except blocks to handle exceptions like HttpError.
-
Feedback to User: After creating the document, consider providing the URL to the user for easy access.
doc_url = f"https://docs.google.com/document/d/{document_id}"
print(f"Document created: {doc_url}")
5. User Interaction Loop
Current Implementation:
while True:
user_input = input("==> ")
if user_input.lower() == "exit":
break
elif user_input.strip() == "":
continue
else:
# Process input
Suggestions:
-
Input Clarity: Prompt the user with clear instructions, so they know how to interact with the script.
print("Enter your request (type 'exit' to quit):")
-
Graceful Exit: Ensure that resources are released properly when the user decides to exit, especially if you have open file handles or network connections.
Additional Recommendations
1. Logging
Implement logging to help with debugging and monitoring.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
Use logger.info(), logger.error(), etc., instead of print() statements.
2. Virtual Environment
Use a virtual environment to manage dependencies, ensuring that your script runs in an isolated environment.
python -m venv venv
source venv/bin/activate # On Windows use venv\Scripts\activate
pip install -r requirements.txt
3. Dependency Management
Create a requirements.txt file to manage your Python dependencies.
torch
transformers
google-auth-oauthlib
google-api-python-client
4. Handling Model and Tokenizer Loading
Since loading large models can be time-consuming, consider loading them only once and reuse them.
5. Improve the Language Model Output Consistency
To get more consistent outputs from the language model:
- Set
temperature=0 to make the model's output more deterministic.
- Increase
num_beams and use beam search for better outputs.
6. Security Considerations
- API Keys and Tokens: Never hard-code API keys or tokens in your script.
- User Input: Always sanitize and validate user input to prevent injection attacks.
7. Documentation
Add docstrings to your functions to explain their purpose, parameters, and return values.
def create_and_write_doc(service, title, content):
"""
Creates a new Google Docs document with the given title and content.
Args:
service: Authorized Google Docs API service instance.
title (str): The title of the document.
content (str): The content to be inserted into the document.
Returns:
bool: True if the document was created successfully, False otherwise.
"""
# Function implementation
8. Exception Handling
Instead of using bare except clauses, catch specific exceptions.
try:
# Some operation
except ValueError as e:
logger.error(f"ValueError occurred: {e}")
except Exception as e:
logger.error(f"An unexpected error occurred: {e}")
Sample Revised Code Snippet
Here's a sample of how you might incorporate some of the suggestions:
import os
import json
import torch
import re
from transformers import AutoTokenizer, AutoModelForCausalLM
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.auth.exceptions import RefreshError
import logging
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Define the scope for Google Docs API
SCOPES = ['https://www.googleapis.com/auth/documents']
def create_and_write_doc(service, title, content):
"""
Creates a new Google Docs document with the given title and content.
Args:
service: Authorized Google Docs API service instance.
title (str): The title of the document.
content (str): The content to be inserted into the document.
Returns:
bool: True if the document was created successfully, False otherwise.
"""
try:
# Sanitize inputs
title = title.strip()
content = content.strip()
# Create a new document
doc = {'title': title}
created_doc = service.documents().create(body=doc).execute()
document_id = created_doc.get('documentId')
# Insert text into the document
requests = [{
'insertText': {
'location': {'index': 1},
'text': content
}
}]
service.documents().batchUpdate(
documentId=document_id,
body={'requests': requests}
).execute()
doc_url = f"https://docs.google.com/document/d/{document_id}"
logger.info(f"Document created: {doc_url}")
return True # Indicate success
except Exception as e:
logger.error(f"Error in creating or writing to the document: {e}")
return False # Indicate failure
def parse_input_with_llm(model, tokenizer, user_input):
"""
Parses the user's input using a language model to extract the title and content.
Args:
model: The loaded language model.
tokenizer: Corresponding tokenizer for the language model.
user_input (str): The user's request string.
Returns:
tuple: A tuple containing the title and content, or (None, None) if parsing fails.
"""
prompt = f"""Extract the document title and content from the following request and return only the JSON object in the format {{"title": "TITLE", "content": "CONTENT"}} without any additional text or explanations.
User request: "{user_input}"
JSON output:
"""
try:
inputs = tokenizer(prompt, return_tensors='pt').to(model.device)
input_ids = inputs['input_ids']
attention_mask = inputs['attention_mask']
# Generate the output
with torch.no_grad():
output_ids = model.generate(
input_ids,
attention_mask=attention_mask,
max_new_tokens=150,
temperature=0, # For deterministic output
do_sample=False,
num_beams=5,
pad_token_id=tokenizer.eos_token_id
)
output_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)
# Extract the JSON output
json_pattern = r'\{[\s\S]*?\}'
matches = re.findall(json_pattern, output_text)
if matches:
json_str = matches[0]
data = json.loads(json_str)
title = data.get('title')
content = data.get('content')
return title, content
else:
logger.error("Could not find JSON in the LLM output.")
logger.debug(f"LLM Output: {output_text}")
return None, None
except Exception as e:
logger.error(f"Error parsing LLM output: {e}")
logger.debug(f"LLM Output: {output_text}")
return None, None
def main():
# Authentication
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
else:
if not os.path.exists('credentials.json'):
logger.error("'credentials.json' file not found.")
return
try:
flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
except Exception as e:
logger.error(f"Error during authentication: {e}")
return
# Build the Docs API service
try:
docs_service = build('docs', 'v1', credentials=creds)
except Exception as e:
logger.error(f"Error building Google Docs API service: {e}")
return
# Load the Hugging Face tokenizer and model
logger.info("Loading Hugging Face model...")
try:
model_name = "gpt2" # Replace with your desired model
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)
model.eval()
logger.info("Model loaded successfully.")
except Exception as e:
logger.error(f"Error loading the model: {e}")
return
# Move model to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Main loop to take user input
print("Enter your request (type 'exit' to quit):")
while True:
user_input = input("==> ")
if user_input.lower() == "exit":
break
elif user_input.strip() == "":
continue
else:
# Parse the user input using the LLM
title, content = parse_input_with_llm(model, tokenizer, user_input)
if title and content:
success = create_and_write_doc(docs_service, title, content)
if success:
logger.info("Document created successfully.")
else:
logger.error("Failed to create the document.")
else:
logger.error("Could not understand your request. Please try again.")
if __name__ == '__main__':
main()
Testing and Validation
- Test the Script: Run the script with various inputs to ensure it behaves as expected.
- Validate Edge Cases: Check how the script handles unexpected inputs or model outputs.
- Monitor Resources: Keep an eye on memory and CPU usage, especially when using large models.
Final Thoughts
Your script is a great starting point for integrating language models with Google Docs. By refining the code based on best practices and handling potential issues proactively, you'll create a robust tool that can serve users effectively.
If you have any specific questions or need further assistance with any part of the script, feel free to ask!