Use Ollama to communicate with a model, for example, Llama 3.2 3B, Phi, gemma3.
We want the model to perform actions on the contents of files.
Allow iteration over a set of txt files in a folder. The contents of these files will be used to communicate with the model.
Add a sentence to the end of the file content, ensuring its length is within the model's context limit.
We have five examples, so generate a code that, in addition to the context it needs to perform, includes a few-shot and a map prompt, because we want that structure a text based on a structure and steps we need to pass to it.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import os
import glob
import requests
# Configuration
MODEL = "llama3.2" # Change to desired model, e.g., "phi", "gemma:3b"
FOLDER_PATH = "path/to/your/folder" # Set this to the directory containing your .txt files
MAX_CONTEXT_CHARS = 4000 # Maximum allowed characters in the prompt; adjust based on model context limit (e.g., ~4096 tokens for Llama 3.2, roughly 4 chars/token)
# Define the few-shot prompt template with examples and steps
FEW_SHOT_PROMPT = """
You are an AI that structures text based on the following steps:
1. Summarize the text in one paragraph.
2. List the key points in bullet form.
3. Provide a conclusion sentence.
Here are five examples to guide your response:
Example 1:
Input: "The sky is blue. Birds fly high."
Output: Summary: The text describes the color of the sky and the flight of birds in a simple manner. Key points: - The sky is blue. - Birds fly high. Conclusion: This highlights everyday observations of nature.
Example 2:
Input: "Python is a programming language. It is easy to learn."
Output: Summary: Python is introduced as an accessible and beginner-friendly programming language. Key points: - Python is a programming language. - It is easy to learn. Conclusion: Learning Python can open doors to software development.
Example 3:
Input: "AI models are advancing rapidly. Ollama allows running them locally."
Output: Summary: The text discusses the fast-paced development of AI models and the role of Ollama in enabling local execution. Key points: - AI models are advancing quickly. - Ollama supports local running of models. Conclusion: Local AI deployment is becoming more practical and efficient.
Example 4:
Input: "Exercise improves health. A balanced diet is important."
Output: Summary: The text emphasizes the benefits of physical activity and proper nutrition for overall well-being. Key points: - Exercise enhances health. - A balanced diet is crucial for nutrition. Conclusion: Adopting healthy habits can lead to a better quality of life.
Example 5:
Input: "Coding is a valuable skill. Practice is essential for mastery."
Output: Summary: Coding is portrayed as an important skill that requires consistent practice to achieve proficiency. Key points: - Coding is a valuable skill. - Practice is key to mastery. Conclusion: Dedicating time to coding can result in significant personal and professional growth.
Now, structure the following text accordingly:
{user_text}
"""
# Function to interact with Ollama API
def generate_with_ollama(prompt, model=MODEL):
url = "http://localhost:11434/api/generate" # Ollama API endpoint
payload = {
"model": model,
"prompt": prompt,
"stream": False # Set to False to get the full response at once
}
try:
response = requests.post(url, json=payload)
if response.status_code == 200:
result = response.json()
generated_text = result.get("response", "").strip() # Extract the generated response
return generated_text
else:
print(f"Error in API call: Status code {response.status_code}, Response: {response.text}")
return None
except Exception as e:
print(f"Exception during API call: {str(e)}")
return None
# Main code to iterate over .txt files and process them
def process_files():
# Get all .txt files in the specified folder
txt_files = glob.glob(os.path.join(FOLDER_PATH, "*.txt"))
if not txt_files:
print("No .txt files found in the specified folder.")
return
for file_path in txt_files:
try:
# Read the file content
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Add a sentence to the end of the file content, as per user request
# This sentence is added to the content before sending to the model
modified_content = content + " Please structure this text based on the provided steps and examples."
# Create the full prompt using the few-shot prompt template
full_prompt = FEW_SHOT_PROMPT.format(user_text=modified_content)
# Ensure the prompt length is within the context limit
if len(full_prompt) > MAX_CONTEXT_CHARS:
# Truncate the modified content to fit within the limit
# Approximate the max content length by subtracting the fixed part of the prompt
prompt_fixed_part = FEW_SHOT_PROMPT.format(user_text="") # Length of prompt without user text
max_user_chars = MAX_CONTEXT_CHARS - len(prompt_fixed_part) - 100 # Subtract a safety margin
if max_user_chars > 0:
truncated_content = modified_content[:max_user_chars] # Simple truncation
full_prompt = FEW_SHOT_PROMPT.format(user_text=truncated_content)
print(f"Prompt exceeded context limit for {file_path}. Content truncated.")
else:
print(f"Prompt too long even after truncation for {file_path}. Skipping file.")
continue
# Send the prompt to Ollama and get the response
generated_text = generate_with_ollama(full_prompt)
if generated_text:
# Save the generated structured text to a new file (e.g., append ".structured" to the original filename)
output_file_path = os.path.join(FOLDER_PATH, os.path.basename(file_path) + ".structured.txt")
with open(output_file_path, 'w', encoding='utf-8') as f:
f.write(generated_text)
print(f"Processed {file_path} and saved structured output to {output_file_path}")
else:
print(f"Failed to generate response for {file_path}")
except Exception as e:
print(f"Error processing file {file_path}: {str(e)}")
# Run the main function
if __name__ == "__main__":
process_files()
Explanation of the Code:
Ollama Integration: The code uses the Ollama API to communicate with a specified model (e.g., Llama 3.2, Phi, or Gemma3). It sends a prompt to the model via a POST request to http://localhost:11434/api/generate. Make sure Ollama is running on your local machine and the desired model is pulled (e.g., via ollama pull llama3.2).
File Iteration: The code iterates over all .txt files in the specified FOLDER_PATH using glob.glob. For each file, it reads the content.
Adding a Sentence: As per your request, a sentence ("Please structure this text based on the provided steps and examples.") is appended to the end of the file content before it is used in the prompt. This ensures the content is modified as specified, and the total length is checked against the context limit.
Context Limit Handling: The code checks the length of the full prompt (in characters) and truncates the file content if it exceeds MAX_CONTEXT_CHARS (set to 4000 by default, which is a conservative estimate for most models). Truncation is done by reducing the length of the modified content, ensuring the prompt fits within the model's context window.
Few-Shot and Map Prompt:
Few-Shot Prompt: The prompt includes five example inputs and outputs to demonstrate how the model should structure the text. This helps the model learn from examples and apply the same structure to new text.
Map Prompt: I interpreted "map prompt" as instructing the model to "map" the text to a specific structure (based on the steps provided). The prompt defines clear steps (summarize, list key points, provide a conclusion) and uses the few-shot examples to guide the mapping process.
Model Response and Output: The model generates a structured response, which is saved to a new file with a .structured.txt extension in the same folder. This avoids overwriting the original files.
Error Handling: The code includes basic error handling for API calls, file reading, and other potential issues. It prints messages for debugging.
How to Use:
Set Configuration: Update MODEL to your desired Ollama model (e.g., "phi" or "gemma:3b"). Set FOLDER_PATH to the directory containing your .txt files.
Run Ollama: Ensure Ollama is installed and running. Pull the model if needed (e.g., ollama pull llama3.2).
Execute the Script: Run the Python script. It will process each .txt file and create new structured output files.
Assumptions: The code assumes the files are small enough or can be truncated. If your files are very large, you may need a more sophisticated token estimation library like tiktoken for better accuracy.
This code fulfills your requirements by combining file iteration, prompt engineering with few-shot learning, context limit enforcement, and model interaction via Ollama. If you need modifications (e.g., different structuring steps or handling for specific models), let me know!