Code Optimization Suggestions
2024-11-174 turns22,876 charsgpt-4o
Summary
improve code and generate ai content with specific styles
Messages
how can I improve this: import logging
import requests
import json
import re
from decouple import config
logger = logging.getLogger(__name__)
XAI_API_KEY = config('XAI_API_KEY')
XAI_API_BASE = "https://api.x.ai/v1"
def analyze_writing_sample(writing_sample):
endpoint = f"{XAI_API_BASE}/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {XAI_API_KEY}"
}
payload = {
"messages": [
{
"role": "system",
"content": "You are an assistant that analyzes writing samples."
},
{
"role": "user",
"content": f'''
Please analyze the writing style and personality of the given writing sample. Provide a detailed assessment of their characteristics using the following template. Rate each applicable characteristic on a scale of 1-10 where relevant, or provide a descriptive value. Return the results in a JSON format.
"name": "[Author/Character Name]",
"vocabulary_complexity": [1-10],
"sentence_structure": "[simple/complex/varied]",
"paragraph_organization": "[structured/loose/stream-of-consciousness]",
"idiom_usage": [1-10],
"metaphor_frequency": [1-10],
"simile_frequency": [1-10],
"tone": "[formal/informal/academic/conversational/etc.]",
"punctuation_style": "[minimal/heavy/unconventional]",
"contraction_usage": [1-10],
"pronoun_preference": "[first-person/third-person/etc.]",
"passive_voice_frequency": [1-10],
"rhetorical_question_usage": [1-10],
"list_usage_tendency": [1-10],
"personal_anecdote_inclusion": [1-10],
"pop_culture_reference_frequency": [1-10],
"technical_jargon_usage": [1-10],
"parenthetical_aside_frequency": [1-10],
"humor_sarcasm_usage": [1-10],
"emotional_expressiveness": [1-10],
"emphatic_device_usage": [1-10],
"quotation_frequency": [1-10],
"analogy_usage": [1-10],
"sensory_detail_inclusion": [1-10],
"onomatopoeia_usage": [1-10],
"alliteration_frequency": [1-10],
"word_length_preference": "[short/long/varied]",
"foreign_phrase_usage": [1-10],
"rhetorical_device_usage": [1-10],
"statistical_data_usage": [1-10],
"personal_opinion_inclusion": [1-10],
"transition_usage": [1-10],
"reader_question_frequency": [1-10],
"imperative_sentence_usage": [1-10],
"dialogue_inclusion": [1-10],
"regional_dialect_usage": [1-10],
"hedging_language_frequency": [1-10],
"language_abstraction": "[concrete/abstract/mixed]",
"personal_belief_inclusion": [1-10],
"repetition_usage": [1-10],
"subordinate_clause_frequency": [1-10],
"verb_type_preference": "[active/stative/mixed]",
"sensory_imagery_usage": [1-10],
"symbolism_usage": [1-10],
"digression_frequency": [1-10],
"formality_level": [1-10],
"reflection_inclusion": [1-10],
"irony_usage": [1-10],
"neologism_frequency": [1-10],
"ellipsis_usage": [1-10],
"cultural_reference_inclusion": [1-10],
"stream_of_consciousness_usage": [1-10],
"openness_to_experience": [1-10],
"conscientiousness": [1-10],
"extraversion": [1-10],
"agreeableness": [1-10],
"emotional_stability": [1-10],
"dominant_motivations": "[achievement/affiliation/power/etc.]",
"core_values": "[integrity/freedom/knowledge/etc.]",
"decision_making_style": "[analytical/intuitive/spontaneous/etc.]",
"empathy_level": [1-10],
"self_confidence": [1-10],
"risk_taking_tendency": [1-10],
"idealism_vs_realism": "[idealistic/realistic/mixed]",
"conflict_resolution_style": "[assertive/collaborative/avoidant/etc.]",
"relationship_orientation": "[independent/communal/mixed]",
"emotional_response_tendency": "[calm/reactive/intense]",
"creativity_level": [1-10],
"age": "[age or age range]",
"gender": "[gender]",
"education_level": "[highest level of education]",
"professional_background": "[brief description]",
"cultural_background": "[brief description]",
"primary_language": "[language]",
"language_fluency": "[native/fluent/intermediate/beginner]",
"background": "[A brief paragraph describing the author's context, major influences, and any other relevant information not captured above]"
Writing Sample:
{writing_sample}
'''
}
],
"model": "grok-beta",
"stream": False,
"temperature": 0
}
try:
response = requests.post(endpoint, headers=headers, json=payload)
response.raise_for_status() # Raises HTTPError for bad responses
# Log the API response for debugging
logger.debug(f"OpenAI API response: {response.text}")
assistant_message = response.json()['choices'][0]['message']['content'].strip()
logger.debug(f"Assistant message: {assistant_message}")
# Extract JSON from the assistant's message
json_str = re.search(r'\{.*\}', assistant_message, re.DOTALL)
if json_str:
analyzed_data = json.loads(json_str.group())
else:
logger.error("No JSON object found in the response.")
return None
return analyzed_data
except requests.exceptions.RequestException as e:
logger.error(f"HTTP Request failed: {e}")
return None
except json.JSONDecodeError as e:
logger.error(f"JSON decoding failed: {e}")
return None
except Exception as e:
logger.error(f"Unexpected error: {e}")
return None
def generate_content(persona_data, prompt):
endpoint = f"{XAI_API_BASE}/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {XAI_API_KEY}"
}
# Format the persona data into a readable string
characteristics = '\n'.join([
f"{key.replace('_', ' ').capitalize()}: {value}"
for key, value in persona_data.items()
if value is not None and key not in ['id', 'name']
])
decoding_prompt = f'''
You are to write a response in the style of {persona_data.get('name', 'Unknown Author')}, a writer with the following characteristics:
{characteristics}
Now, please write a response in this style about the following topic:
"{prompt}"
Begin with a compelling title that reflects the content of the post.
'''
payload = {
"messages": [
{"role": "system", "content": "You are an assistant that generates blog posts."},
{"role": "user", "content": decoding_prompt}
],
"model": "grok-beta",
"stream": False,
"temperature": 0
}
try:
response = requests.post(endpoint, headers=headers, json=payload)
response.raise_for_status()
assistant_message = response.json()['choices'][0]['message']['content'].strip()
logger.debug(f"Assistant message: {assistant_message}")
return assistant_message
except requests.exceptions.RequestException as e:
logger.error(f"HTTP Request failed: {e}")
return ''
except json.JSONDecodeError as e:
logger.error(f"JSON decoding failed: {e}")
return ''
except Exception as e:
logger.error(f"Unexpected error: {e}")
return ''
def save_blog_post(blog_post, title):
# Implement if needed
pass
Your code is well-structured but can be improved for readability, maintainability, and error handling. Here are some suggestions:
### Improvements
1. **Separation of Concerns**: Split the code into smaller functions to handle specific tasks (e.g., making API requests, extracting JSON, and formatting data).
2. **Logging**: Add more detailed log messages, including when entering/exiting functions, and make logs consistent.
3. **DRY Principle**: Avoid repeating API request logic. Create a helper function to handle HTTP requests.
4. **Error Messages**: Make error logs more descriptive to aid debugging.
5. **Static Analysis**: Use type hints to clarify expected input and output types.
6. **Default Configuration Handling**: Add a fallback for environment variables using `os.environ.get()` to avoid failures in development or testing environments.
### Refactored Code
Here's a cleaner, modular version of your code:
```python
import logging
import requests
import json
import re
from typing import Optional, Dict, Any
from decouple import config
# Configure logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # Adjust logging level as needed
XAI_API_KEY = config("XAI_API_KEY", default="your_default_api_key")
XAI_API_BASE = "https://api.x.ai/v1"
def make_api_request(endpoint: str, payload: dict, headers: dict) -> Optional[dict]:
"""
Helper function to send POST requests to the API.
"""
try:
response = requests.post(endpoint, headers=headers, json=payload)
response.raise_for_status() # Raise HTTPError for bad responses
logger.debug(f"API Response: {response.text}")
return response.json()
except requests.exceptions.RequestException as e:
logger.error(f"HTTP request failed: {e}")
except json.JSONDecodeError as e:
logger.error(f"Failed to decode JSON: {e}")
return None
def extract_json_from_message(message: str) -> Optional[dict]:
"""
Extract a JSON object from a string.
"""
try:
json_str = re.search(r"\{.*\}", message, re.DOTALL)
if json_str:
return json.loads(json_str.group())
logger.warning("No JSON object found in the message.")
except json.JSONDecodeError as e:
logger.error(f"Error decoding JSON from message: {e}")
return None
def analyze_writing_sample(writing_sample: str) -> Optional[dict]:
"""
Analyze the given writing sample and return its analysis as a dictionary.
"""
endpoint = f"{XAI_API_BASE}/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {XAI_API_KEY}"
}
payload = {
"messages": [
{"role": "system", "content": "You are an assistant that analyzes writing samples."},
{"role": "user", "content": f"Please analyze the writing sample:\n{writing_sample}"}
],
"model": "grok-beta",
"stream": False,
"temperature": 0
}
api_response = make_api_request(endpoint, payload, headers)
if not api_response:
return None
assistant_message = api_response.get('choices', [{}])[0].get('message', {}).get('content', "").strip()
logger.debug(f"Assistant message: {assistant_message}")
return extract_json_from_message(assistant_message)
def format_persona_data(persona_data: Dict[str, Any]) -> str:
"""
Format persona data into a readable string for use in prompts.
"""
return "\n".join(
f"{key.replace('_', ' ').capitalize()}: {value}"
for key, value in persona_data.items()
if value is not None
)
def generate_content(persona_data: dict, prompt: str) -> str:
"""
Generate content based on persona data and a given prompt.
"""
endpoint = f"{XAI_API_BASE}/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {XAI_API_KEY}"
}
characteristics = format_persona_data(persona_data)
decoding_prompt = f"""
Write a response in the style of {persona_data.get('name', 'Unknown Author')}:
{characteristics}
Topic: "{prompt}"
"""
payload = {
"messages": [
{"role": "system", "content": "You are an assistant that generates content."},
{"role": "user", "content": decoding_prompt}
],
"model": "grok-beta",
"stream": False,
"temperature": 0
}
api_response = make_api_request(endpoint, payload, headers)
if not api_response:
return ""
return api_response.get('choices', [{}])[0].get('message', {}).get('content', "").strip()
def save_blog_post(blog_post: str, title: str):
"""
Save a blog post (implement if needed).
"""
# Placeholder for saving logic
logger.info(f"Saving blog post titled '{title}'.")
```
### Key Changes
1. **Helper Functions**:
- `make_api_request`: Handles API requests consistently.
- `extract_json_from_message`: Centralized JSON extraction logic.
- `format_persona_data`: Creates readable prompt content.
2. **Error Handling**:
- More descriptive logging at every failure point.
3. **Type Hints**:
- Clarifies expected input and return types.
4. **Readable Prompt Formatting**:
- Simplifies `generate_content` prompt construction.
This refactored version is more modular and easier to maintain. You can add unit tests for individual functions like `extract_json_from_message` and `make_api_request` to ensure reliability.
gpt-4o
Write the following values in a prompt, allowing fstrings to be used to fill in the prompt with the values that the keys represent. The prompt should help the LLM generate content in a way that captures the style of the values. Each value should have a descriptive instruction on how to use that value.
"name": "[Author/Character Name]",
"vocabulary_complexity": [1-10],
"sentence_structure": "[simple/complex/varied]",
"paragraph_organization": "[structured/loose/stream-of-consciousness]",
"idiom_usage": [1-10],
"metaphor_frequency": [1-10],
"simile_frequency": [1-10],
"tone": "[formal/informal/academic/conversational/etc.]",
"punctuation_style": "[minimal/heavy/unconventional]",
"contraction_usage": [1-10],
"pronoun_preference": "[first-person/third-person/etc.]",
"passive_voice_frequency": [1-10],
"rhetorical_question_usage": [1-10],
"list_usage_tendency": [1-10],
"personal_anecdote_inclusion": [1-10],
"pop_culture_reference_frequency": [1-10],
"technical_jargon_usage": [1-10],
"parenthetical_aside_frequency": [1-10],
"humor_sarcasm_usage": [1-10],
"emotional_expressiveness": [1-10],
"emphatic_device_usage": [1-10],
"quotation_frequency": [1-10],
"analogy_usage": [1-10],
"sensory_detail_inclusion": [1-10],
"onomatopoeia_usage": [1-10],
"alliteration_frequency": [1-10],
"word_length_preference": "[short/long/varied]",
"foreign_phrase_usage": [1-10],
"rhetorical_device_usage": [1-10],
"statistical_data_usage": [1-10],
"personal_opinion_inclusion": [1-10],
"transition_usage": [1-10],
"reader_question_frequency": [1-10],
"imperative_sentence_usage": [1-10],
"dialogue_inclusion": [1-10],
"regional_dialect_usage": [1-10],
"hedging_language_frequency": [1-10],
"language_abstraction": "[concrete/abstract/mixed]",
"personal_belief_inclusion": [1-10],
"repetition_usage": [1-10],
"subordinate_clause_frequency": [1-10],
"verb_type_preference": "[active/stative/mixed]",
"sensory_imagery_usage": [1-10],
"symbolism_usage": [1-10],
"digression_frequency": [1-10],
"formality_level": [1-10],
"reflection_inclusion": [1-10],
"irony_usage": [1-10],
"neologism_frequency": [1-10],
"ellipsis_usage": [1-10],
"cultural_reference_inclusion": [1-10],
"stream_of_consciousness_usage": [1-10],
"openness_to_experience": [1-10],
"conscientiousness": [1-10],
"extraversion": [1-10],
"agreeableness": [1-10],
"emotional_stability": [1-10],
"dominant_motivations": "[achievement/affiliation/power/etc.]",
"core_values": "[integrity/freedom/knowledge/etc.]",
"decision_making_style": "[analytical/intuitive/spontaneous/etc.]",
"empathy_level": [1-10],
"self_confidence": [1-10],
"risk_taking_tendency": [1-10],
"idealism_vs_realism": "[idealistic/realistic/mixed]",
"conflict_resolution_style": "[assertive/collaborative/avoidant/etc.]",
"relationship_orientation": "[independent/communal/mixed]",
"emotional_response_tendency": "[calm/reactive/intense]",
"creativity_level": [1-10],
"age": "[age or age range]",
"gender": "[gender]",
"education_level": "[highest level of education]",
"professional_background": "[brief description]",
"cultural_background": "[brief description]",
"primary_language": "[language]",
"language_fluency": "[native/fluent/intermediate/beginner]",
"background": "[A brief paragraph describing the author's context, major influences, and any other relevant information not captured above]"
Here’s a detailed prompt template with f-strings for each key, ensuring the LLM utilizes the values to shape its output:
---
**Prompt: Generating Content in the Style of {name}**
You are to generate content that captures the distinct style and personality of {name}. Follow the detailed instructions for each characteristic below to craft content that mirrors their writing tendencies and persona.
### Writing Style Characteristics:
1. **Vocabulary Complexity ({vocabulary_complexity}/10):** Use words with a complexity level that matches this score. For higher scores, include sophisticated vocabulary; for lower scores, stick to simpler, more accessible terms.
2. **Sentence Structure ({sentence_structure}):** Write sentences that align with this structure, whether simple, complex, or varied.
3. **Paragraph Organization ({paragraph_organization}):** Structure paragraphs in the described manner—whether tightly structured, loosely organized, or stream-of-consciousness.
4. **Idiom Usage ({idiom_usage}/10):** Include idioms at a frequency corresponding to this score.
5. **Metaphor Frequency ({metaphor_frequency}/10):** Incorporate metaphors at the indicated level of frequency.
6. **Simile Frequency ({simile_frequency}/10):** Use similes as often as specified by this score.
### Tone and Language:
7. **Tone ({tone}):** Maintain the tone specified, such as formal, conversational, academic, or otherwise.
8. **Punctuation Style ({punctuation_style}):** Use punctuation in the specified manner—whether minimal, heavy, or unconventional.
9. **Contraction Usage ({contraction_usage}/10):** Use contractions (e.g., "don't," "can't") at the frequency indicated by this score.
10. **Pronoun Preference ({pronoun_preference}):** Frame the narrative using the specified pronouns (e.g., first-person, third-person).
### Writing Techniques:
11. **Passive Voice Frequency ({passive_voice_frequency}/10):** Include passive voice constructions to match this frequency.
12. **Rhetorical Question Usage ({rhetorical_question_usage}/10):** Add rhetorical questions as frequently as indicated.
13. **List Usage Tendency ({list_usage_tendency}/10):** Use lists with the specified level of frequency.
### Content Inclusions:
14. **Personal Anecdote Inclusion ({personal_anecdote_inclusion}/10):** Include personal anecdotes at the indicated level.
15. **Pop Culture Reference Frequency ({pop_culture_reference_frequency}/10):** Add pop culture references as frequently as specified.
16. **Technical Jargon Usage ({technical_jargon_usage}/10):** Incorporate technical jargon to match this frequency.
### Additional Stylistic Elements:
17. **Parenthetical Aside Frequency ({parenthetical_aside_frequency}/10):** Add parenthetical asides (e.g., "(this is an aside)") as frequently as specified.
18. **Humor/Sarcasm Usage ({humor_sarcasm_usage}/10):** Use humor or sarcasm at the indicated level.
19. **Emotional Expressiveness ({emotional_expressiveness}/10):** Convey emotions with intensity matching this score.
20. **Emphatic Device Usage ({emphatic_device_usage}/10):** Use emphatic devices (e.g., exclamation points, italics) at the specified frequency.
### Deeper Style Insights:
21. **Quotations ({quotation_frequency}/10):** Incorporate direct quotes at the specified frequency.
22. **Analogies ({analogy_usage}/10):** Include analogies as frequently as indicated.
23. **Sensory Details ({sensory_detail_inclusion}/10):** Use sensory-rich descriptions at this frequency.
### Personal Context and Psychology:
24. **Age ({age}):** Consider the author's age when generating perspectives or tone.
25. **Gender ({gender}):** Reflect any relevant influences of the author’s gender.
26. **Education Level ({education_level}):** Incorporate the depth of knowledge corresponding to this level.
27. **Professional Background ({professional_background}):** Use the provided professional context to shape the content.
28. **Cultural Background ({cultural_background}):** Reflect cultural influences where relevant.
29. **Primary Language ({primary_language}):** Ensure the language fluency ({language_fluency}) aligns with the specified level.
### Persona Details:
30. **Dominant Motivations ({dominant_motivations}):** Let the character’s motivations influence the narrative direction.
31. **Core Values ({core_values}):** Infuse the content with values that align with these principles.
32. **Conflict Resolution Style ({conflict_resolution_style}):** Include interactions that reflect this style when applicable.
---
**Topic:** {topic}
Now, write a compelling, engaging, and authentic piece based on the topic provided, ensuring every stylistic element above is reflected accurately in your output.
gpt-4o