Below is a Python script that fulfills your requirements. It uses the ollama Python package to communicate with a model (e.g., Llama 3.2 3B, Phi, or Gemma3). The script iterates over .txt files in a folder, modifies their content by appending a sentence, ensures the context length is within the model's limit, and includes few-shot examples and a map prompt for structured responses.
Prerequisites:
- Install the
ollama Python package:
pip install ollama
- Ensure you have Ollama installed and running locally. You can download it from here.
Python Code
import os
from ollama import Client
# Initialize Ollama client
client = Client()
# Folder containing the .txt files
input_folder = "path/to/your/txt/files"
output_folder = "path/to/save/modified/files"
# Model name (replace with your desired model)
model_name = "llama3.2:3b" # Example: "phi" or "gemma3"
# Few-shot examples for guiding the model
few_shot_examples = """
Example 1:
Input: "The quick brown fox jumps over the lazy dog."
Output: "The quick brown fox jumps over the lazy dog. This sentence demonstrates all the letters of the alphabet."
Example 2:
Input: "Artificial intelligence is transforming industries."
Output: "Artificial intelligence is transforming industries. Its applications range from healthcare to finance."
Example 3:
Input: "Python is a versatile programming language."
Output: "Python is a versatile programming language. It is widely used in data science, web development, and automation."
"""
# Map prompt for structuring the response
map_prompt = """
You are tasked with analyzing and enhancing the given text. Follow these steps:
1. Read the input text carefully.
2. Append a meaningful sentence to the end of the text.
3. Ensure the total length of the text does not exceed the model's context limit.
4. Return the enhanced text.
"""
# Function to process each file
def process_file(file_path, output_folder):
# Read the file content
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
# Add a sentence to the content
modified_content = content + " Analyze this text and provide insights."
# Ensure the content is within the model's context limit (e.g., 4096 tokens)
max_context_length = 4096
if len(modified_content.split()) > max_context_length:
modified_content = " ".join(modified_content.split()[:max_context_length])
# Prepare the full prompt with few-shot examples and map prompt
full_prompt = f"""
{few_shot_examples}
{map_prompt}
Input: "{modified_content}"
Output:
"""
# Communicate with the model
response = client.chat(
model=model_name,
messages=[{"role": "user", "content": full_prompt}]
)
# Extract the model's response
enhanced_text = response["message"]["content"]
# Save the enhanced text to a new file
output_file_path = os.path.join(output_folder, os.path.basename(file_path))
with open(output_file_path, "w", encoding="utf-8") as file:
file.write(enhanced_text)
print(f"Processed and saved: {output_file_path}")
# Main function to iterate over files in the folder
def main():
# Create the output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)
# Iterate over all .txt files in the input folder
for filename in os.listdir(input_folder):
if filename.endswith(".txt"):
file_path = os.path.join(input_folder, filename)
process_file(file_path, output_folder)
if __name__ == "__main__":
main()
Explanation of the Code:
-
Ollama Integration:
- The
ollama Python package is used to communicate with the specified model (model_name).
- The
client.chat method sends a prompt to the model and retrieves its response.
-
File Iteration:
- The script iterates over all
.txt files in the input_folder.
- Each file's content is read and modified by appending a sentence.
-
Context Length Check:
- The script ensures the modified content does not exceed the model's context limit (e.g., 4096 tokens).
-
Few-Shot Examples and Map Prompt:
- The
few_shot_examples variable provides examples to guide the model.
- The
map_prompt defines the structure and steps the model should follow.
-
Output:
- The enhanced text generated by the model is saved in the
output_folder.
Example Input File (example.txt):
The quick brown fox jumps over the lazy dog.
Example Output File (example.txt):
The quick brown fox jumps over the lazy dog. Analyze this text and provide insights. This sentence demonstrates all the letters of the alphabet.
Notes:
- Replace
"path/to/your/txt/files" and "path/to/save/modified/files" with the actual paths to your input and output folders.
- Adjust the
model_name to match the model you want to use.
- Modify the
max_context_length if your model has a different context limit.
This script is modular and can be extended or customized based on additional requirements.