def is_valid_proposition(self, proposition):
# Entferne führende und nachgestellte Leerzeichen und prüfe, ob es mehr als 4 Wörter sind
words = proposition.strip().split()
# Überprüfe, ob mehr als 4 Wörter vorhanden sind und ob der Satz nicht mit einer Zahl beginnt
if len(words) > 5 and not words[0].isdigit():
return True
# Protokolliere, warum ein Satz ignoriert wird
if self.print_logging:
if len(words) <= 5:
print(f"Ignored short proposition (less than 5 words): '{proposition}'")
if words[0].isdigit():
print(f"Ignored proposition starting with a number: '{proposition}'")
return False
def add_propositions(self, propositions):
for proposition in propositions:
if self.is_valid_proposition(proposition):
self.add_proposition(proposition)
elif self.print_logging:
print(f"Ignored invalid or short proposition: '{proposition}'")
def read_propositions_from_file(self, file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return [line.strip() for line in file if line.strip()]
def _get_completion(self, messages):
# Konsolidieren Sie die system- und benutzerbezogene Inhalte in eine einzige Nachricht
user_message_content = "\n\n".join([msg["content"] for msg in messages if msg["role"] == "user"])
system_message_content = "\n\n".join([msg["content"] for msg in messages if msg["role"] == "system"])
# Als Einzelnachricht senden
consolidated_message = f"System:\n{system_message_content}\n\nUser:\n{user_message_content}"
response = ollama.chat(model=self.MODEL, messages=[
{'role': 'user', 'content': consolidated_message}
])
return response['message']['content'].strip()
def add_proposition(self, proposition):
if self.print_logging:
print(f"\nAdding: '{proposition}'")
if len(self.chunks) == 0:
if self.print_logging:
print("No chunks, creating a new one")
self._create_new_chunk(proposition)
return
chunk_id = self._find_relevant_chunk(proposition)
#Prüfung chunk-id
print("chunk-id-reinhard:", chunk_id)
if chunk_id:
if self.print_logging:
print(f"Chunk Found ({self.chunks[chunk_id]['chunk_id']}), adding to: {self.chunks[chunk_id]['title']}")
self.add_proposition_to_chunk(chunk_id, proposition)
else:
if self.print_logging:
print("No chunks found")
self._create_new_chunk(proposition)
def add_proposition_to_chunk(self, chunk_id, proposition):
self.chunks[chunk_id]['propositions'].append(proposition)
if self.generate_new_metadata_ind:
self.chunks[chunk_id]['summary'] = self._update_chunk_summary(self.chunks[chunk_id])
self.chunks[chunk_id]['title'] = self._update_chunk_title(self.chunks[chunk_id])
def _update_chunk_summary(self, chunk):
messages = [
{"role": "system", "content": """
You are the steward of a group of chunks which represent groups of sentences that talk about a similar topic.
A new proposition was just added to one of your chunks, you should generate a very brief 1-sentence summary which will inform viewers what a chunk group is about.
A good summary will say what the chunk is about, and give any clarifying instructions on what to add to the chunk.
Your summaries should anticipate generalization. If you get a proposition about apples, generalize it to food.
Or month, generalize it to "date and times".
Only respond in german with the chunk new summary, nothing else.print
"""},
{"role": "user", "content": f"Chunk's propositions:\n{' '.join(chunk['propositions'])}\n\nCurrent chunk summary:\n{chunk['summary']}"}
]
return self._get_completion(messages)
def _update_chunk_title(self, chunk):
messages = [
{"role": "system", "content": """
You are the steward of a group of chunks which represent groups of sentences that talk about a similar topic.
A new proposition was just added to one of your chunks, you should generate a very brief updated chunk title which will inform viewers what a chunk group is about.
A good title will say what the chunk is about.
Your title should anticipate generalization. If you get a proposition about apples, generalize it to food.
Or month, generalize it to "date and times".
Only respond in german with the new chunk title, nothing else.
"""},
{"role": "user", "content": f"Chunk's propositions:\n{' '.join(chunk['propositions'])}\n\nChunk summary:\n{chunk['summary']}\n\nCurrent chunk title:\n{chunk['title']}"}
]
return self._get_completion(messages)
def _get_new_chunk_summary(self, proposition):
messages = [
{"role": "system", "content": """
You are the steward of a group of chunks which represent groups of sentences that talk about a similar topic.
You should generate a very brief 1-sentence summary which will inform viewers what a chunk group is about.
A good summary will say what the chunk is about, and give any clarifying instructions on what to add to the chunk.
Your summaries should anticipate generalization. If you get a proposition about apples, generalize it to food.
Or month, generalize it to "date and times".
Only respond in german with the new chunk summary, nothing else.
"""},
{"role": "user", "content": f"Determine the summary of the new chunk that this proposition will go into:\n{proposition}"}
]
return self._get_completion(messages)
def _get_new_chunk_title(self, summary):
messages = [
{"role": "system", "content": """
You are the steward of a group of chunks which represent groups of sentences that talk about a similar topic.
You should generate a very brief few word chunk title which will inform viewers what a chunk group is about.
A good chunk title is brief but encompasses what the chunk is about.
Your titles should anticipate generalization. If you get a proposition about apples, generalize it to food.
Or month, generalize it to "date and times".
Only respond in german with the new chunk title, nothing else.
"""},
{"role": "user", "content": f"Determine the title of the chunk that this summary belongs to:\n{summary}"}
]
return self._get_completion(messages)
def _create_new_chunk(self, proposition):
new_chunk_id = str(uuid.uuid4())[:self.id_truncate_limit]
new_chunk_summary = self._get_new_chunk_summary(proposition)
new_chunk_title = self._get_new_chunk_title(new_chunk_summary)
self.chunks[new_chunk_id] = {
'chunk_id': new_chunk_id,
'propositions': [proposition],
'title': new_chunk_title,
'summary': new_chunk_summary,
'chunk_index': len(self.chunks)
}
if self.print_logging:
print(f"Created new chunk ({new_chunk_id}): {new_chunk_title}")
def get_chunk_outline(self):
chunk_outline = ""
for chunk_id, chunk in self.chunks.items():
chunk_outline += f"Chunk ID: {chunk['chunk_id']}\nChunk Name: {chunk['title']}\nChunk Summary: {chunk['summary']}\n\n"
return chunk_outline
def _find_relevant_chunk(self, proposition):
current_chunk_outline = self.get_chunk_outline()
messages = [
{"role": "system", "content": """
Du bist ein hochspezialisierter Algorithmus zur Kategorisierung landwirtschaftlicher Daten. Deine Aufgabe ist es, neue Informationen in eine bestehende Kategorie einzuordnen, oder eine neue Kategorie vorzuschlagen. Du hast Zugriff auf eine Reihe von Chunk-Summaries, die bereits bestehenden Kategorien zugeordnet sind.
So gehst du vor:
Durchsuche gezielt: Analysiere jeden Chunk-Summary und vergleiche ihn systematisch mit den neuen Informationen, um zu bestimmen, ob eine bestehende Kategorie passt.
Dynamische Identifikation: Triff eine Auswahl auf Grundlage des Inhalts, nicht anhand der Beispiele. Solltest du eine Kategorie finden, die passt, extrahiere die konkrete 5-stellige chunk_id, die mit dieser Kategorie verbunden ist. Antworte mit dieser ID allein, ohne Variationen oder zusätzliche Begriffe.
Fehlende Übereinstimmung: Falls keine vorhandene Kategorie den neuen Informationen entspricht, antworte genau mit „Neue Kategorie“.
Wichtiger Hinweis:
Exklusive Ausgabe: Gib niemals die chunk_id aus den Beispielantworten zurück. Deine Antworten müssen jede Interaktion basierend auf den tatsächlichen Daten abhandeln.
Präzise Antworten: In deiner Antwort darf nur die passende chunk_id oder der Text „Neue Kategorie“ stehen. Keine Erläuterungen oder zusätzlichen Textelemente.
"""},
{"role": "user", "content": f"Current Chunks:\n--Start of current chunks--\n{current_chunk_outline}\n--End of current chunks--"},
{"role": "user", "content": f"Determine if the following statement should belong to one of the chunks outlined:\n{proposition}"}
]
chunk_found = self._get_completion(messages)
print("Chunk found:", chunk_found)
if chunk_found not in self.chunks:
print("No existing chunk found, possibly a new category.")
return None
return chunk_found
def get_chunks(self, get_type='dict'):
if get_type == 'dict':
return self.chunks
if get_type == 'list_of_strings':
return [" ".join(chunk['propositions']) for chunk in self.chunks.values()]
def pretty_print_chunks(self):
print(f"\nYou have {len(self.chunks)} chunks\n")
for chunk_id, chunk in self.chunks.items():
print(f"Chunk #{chunk['chunk_index']}")
print(f"Chunk ID: {chunk_id}")
print(f"Summary: {chunk['summary']}")
print(f"Propositions:")
for prop in chunk['propositions']:
print(f" -{prop}")
print("\n\n")
def pretty_print_chunk_outline(self):
print("Chunk Outline\n")
print(self.get_chunk_outline())
import dspy # Annahme: dspy importieren
import uuid
import sys
from typing import Optional
from pydantic import BaseModel
class AgenticChunker:
def __init__(self):
self.chunks = {}
self.id_truncate_limit = 5
self.generate_new_metadata_ind = True
self.print_logging = True
self.MODEL = 'llama3.2:latest' # Verwenden Sie hier den korrekten Modellnamen für Llama 3.2 8B
def is_valid_proposition(self, proposition):
# Entferne führende und nachgestellte Leerzeichen und prüfe, ob es mehr als 4 Wörter sind
words = proposition.strip().split()
# Überprüfe, ob mehr als 4 Wörter vorhanden sind und ob der Satz nicht mit einer Zahl beginnt
if len(words) > 5 and not words[0].isdigit():
return True
# Protokolliere, warum ein Satz ignoriert wird
if self.print_logging:
if len(words) <= 5:
print(f"Ignored short proposition (less than 5 words): '{proposition}'")
if words[0].isdigit():
print(f"Ignored proposition starting with a number: '{proposition}'")
return False
def add_propositions(self, propositions):
for proposition in propositions:
if self.is_valid_proposition(proposition):
self.add_proposition(proposition)
elif self.print_logging:
print(f"Ignored invalid or short proposition: '{proposition}'")
def read_propositions_from_file(self, file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return [line.strip() for line in file if line.strip()]
def _get_completion(self, messages):
# Konsolidieren Sie die system- und benutzerbezogene Inhalte in eine einzige Nachricht
user_message_content = "\n\n".join([msg["content"] for msg in messages if msg["role"] == "user"])
system_message_content = "\n\n".join([msg["content"] for msg in messages if msg["role"] == "system"])
# Als Einzelnachricht senden
consolidated_message = f"System:\n{system_message_content}\n\nUser:\n{user_message_content}"
# Annahme: Ändere hier zu dspy
response = dspy.chat(model=self.MODEL, messages=[
{'role': 'user', 'content': consolidated_message}
])
return response['message']['content'].strip()
def add_proposition(self, proposition):
if self.print_logging:
print(f"\nAdding: '{proposition}'")
if len(self.chunks) == 0:
if self.print_logging:
print("No chunks, creating a new one")
self._create_new_chunk(proposition)
return
chunk_id = self._find_relevant_chunk(proposition)
print("chunk-id-reinhard:", chunk_id)
if chunk_id:
if self.print_logging:
print(f"Chunk Found ({self.chunks[chunk_id]['chunk_id']}), adding to: {self.chunks[chunk_id]['title']}")
self.add_proposition_to_chunk(chunk_id, proposition)
else:
if self.print_logging:
print("No chunks found")
self._create_new_chunk(proposition)
def add_proposition_to_chunk(self, chunk_id, proposition):
self.chunks[chunk_id]['propositions'].append(proposition)
if self.generate_new_metadata_ind:
self.chunks[chunk_id]['summary'] = self._update_chunk_summary(self.chunks[chunk_id])
self.chunks[chunk_id]['title'] = self._update_chunk_title(self.chunks[chunk_id])
def _update_chunk_summary(self, chunk):
...
return self._get_completion(messages)
def _update_chunk_title(self, chunk):
...
return self._get_completion(messages)
def _get_new_chunk_summary(self, proposition):
...
return self._get_completion(messages)
def _get_new_chunk_title(self, summary):
...
return self._get_completion(messages)
def _create_new_chunk(self, proposition):
new_chunk_id = str(uuid.uuid4())[:self.id_truncate_limit]
new_chunk_summary = self._get_new_chunk_summary(proposition)
new_chunk_title = self._get_new_chunk_title(new_chunk_summary)
self.chunks[new_chunk_id] = {
'chunk_id': new_chunk_id,
'propositions': [proposition],
'title': new_chunk_title,
'summary': new_chunk_summary,
'chunk_index': len(self.chunks)
}
if self.print_logging:
print(f"Created new chunk ({new_chunk_id}): {new_chunk_title}")
def get_chunk_outline(self):
chunk_outline = ""
for chunk_id, chunk in self.chunks.items():
chunk_outline += f"Chunk ID: {chunk['chunk_id']}\nChunk Name: {chunk['title']}\nChunk Summary: {chunk['summary']}\n\n"
return chunk_outline
def _find_relevant_chunk(self, proposition):
current_chunk_outline = self.get_chunk_outline()
...
chunk_found = self._get_completion(messages)
print("Chunk found:", chunk_found)
if chunk_found not in self.chunks:
print("No existing chunk found, possibly a new category.")
return None
return chunk_found
def get_chunks(self, get_type='dict'):
if get_type == 'dict':
return self.chunks
if get_type == 'list_of_strings':
return [" ".join(chunk['propositions']) for chunk in self.chunks.values()]
def pretty_print_chunks(self):
print(f"\nYou have {len(self.chunks)} chunks\n")
for chunk_id, chunk in self.chunks.items():
print(f"Chunk #{chunk['chunk_index']}")
print(f"Chunk ID: {chunk_id}")
print(f"Summary: {chunk['summary']}")
print(f"Propositions:")
for prop in chunk['propositions']:
print(f" -{prop}")
print("\n\n")
def pretty_print_chunk_outline(self):
print("Chunk Outline\n")
print(self.get_chunk_outline())
if __name__ == "__main__":
ac = AgenticChunker()
# Pfad zur Textdatei mit den Propositionen
file_path = "input.txt" # Stellen Sie sicher, dass dieser Pfad korrekt ist
# Lesen Sie die Propositionen aus der Datei
propositions = ac.read_propositions_from_file(file_path)
# Fügen Sie die gelesenen Propositionen hinzu
ac.add_propositions(propositions)
# Umleiten der Standardausgabe in eine Datei
original_stdout = sys.stdout
with open('output.txt', 'w', encoding='utf-8') as f:
sys.stdout = f
ac.pretty_print_chunks()
ac.pretty_print_chunk_outline()
sys.stdout = original_stdout
print("Die Ergebnisse wurden in 'output.txt' geschrieben.")