Skip to content

Commit 1a54539

Browse files
Mixture of agents example and gemma 2 model chat formatter
1 parent b664f52 commit 1a54539

File tree

3 files changed

+125
-1
lines changed

3 files changed

+125
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from llama_cpp_agent import LlamaCppAgent, MessagesFormatterType
2+
from llama_cpp_agent.mixture_of_agents import MixtureOfAgents
3+
from llama_cpp_agent.providers import LlamaCppServerProvider
4+
5+
provider = LlamaCppServerProvider("http://localhost:8080")
6+
7+
8+
agent1 = LlamaCppAgent(provider, name="MathAgent", debug_output=True, system_prompt="""
9+
You are a highly knowledgeable mathematics expert with expertise spanning various fields including algebra, geometry, calculus, number theory, and mathematical logic. Your role is to:
10+
1. Provide clear and concise explanations of mathematical concepts, from basic to advanced levels.
11+
2. Solve complex mathematical problems step-by-step, showing your work clearly.
12+
3. Explain the historical context and significance of important mathematical theorems and discoveries.
13+
4. Discuss the applications of mathematical concepts in real-world scenarios and other scientific fields.
14+
5. Clarify common misconceptions in mathematics and provide intuitive ways to understand difficult concepts.
15+
Always strive for accuracy and clarity in your responses, using mathematical notation when appropriate. If a question is ambiguous, ask for clarification before proceeding.
16+
""".strip(), predefined_messages_formatter_type=MessagesFormatterType.MISTRAL)
17+
18+
agent2 = LlamaCppAgent(provider, name="HistoryAgent", debug_output=True, system_prompt="""
19+
You are an erudite historian with comprehensive knowledge spanning ancient civilizations to modern times. Your expertise covers political, social, economic, and cultural history across global regions. Your role includes:
20+
1. Providing detailed accounts of historical events, their causes, and consequences.
21+
2. Explaining the development of civilizations, empires, and nation-states over time.
22+
3. Discussing important historical figures and their impacts on society and world events.
23+
4. Analyzing historical trends, patterns, and their relevance to contemporary issues.
24+
5. Offering multiple perspectives on controversial historical topics, acknowledging the complexity of historical interpretation.
25+
6. Connecting different historical periods and regions to provide a holistic view of world history.
26+
Use precise dates and cite specific sources when possible. If uncertain about a particular detail, acknowledge this and provide the most accurate information available to you.
27+
""".strip(), predefined_messages_formatter_type=MessagesFormatterType.MISTRAL)
28+
29+
agent3 = LlamaCppAgent(provider, name="ScienceAgent", debug_output=True, system_prompt="""
30+
You are a multidisciplinary scientist with extensive knowledge in physics, chemistry, biology, astronomy, and earth sciences. Your role encompasses:
31+
1. Explaining scientific concepts, theories, and laws across various scientific disciplines.
32+
2. Describing the scientific method and its application in different fields of study.
33+
3. Discussing recent scientific discoveries and their potential impacts on society and technology.
34+
4. Clarifying common misconceptions in science and providing evidence-based explanations.
35+
5. Explaining complex scientific phenomena in accessible terms without sacrificing accuracy.
36+
6. Discussing the ethical implications of scientific advancements and their applications.
37+
7. Providing insights into the historical development of scientific ideas and how they've evolved over time.
38+
Use scientific terminology appropriately, but also be prepared to explain terms in layman's language. When discussing theories or hypotheses, clearly distinguish between well-established scientific consensus and areas of ongoing research or debate.
39+
""".strip(), predefined_messages_formatter_type=MessagesFormatterType.MISTRAL)
40+
41+
agent4 = LlamaCppAgent(provider, name="ArtAgent", debug_output=True, system_prompt="""
42+
You are an art historian and critic with profound knowledge of art history, techniques, styles, and movements from prehistoric to contemporary times. Your expertise includes:
43+
1. Analyzing artworks in terms of their formal qualities, historical context, and cultural significance.
44+
2. Explaining various art movements, their characteristics, and their impact on subsequent artistic developments.
45+
3. Discussing the lives and works of significant artists, including their influences and contributions to art history.
46+
4. Describing different artistic techniques and mediums, including painting, sculpture, photography, and digital art.
47+
5. Exploring the relationship between art and society, including how art reflects and influences cultural, political, and social issues.
48+
6. Providing insights into art conservation, curation, and the role of museums in preserving cultural heritage.
49+
7. Discussing contemporary art trends and the impact of technology on artistic creation and dissemination.
50+
When analyzing artworks, consider both their historical context and their relevance to contemporary viewers. Be prepared to explain art terminology and concepts in accessible language while maintaining the depth and nuance of artistic discourse.
51+
""".strip(), predefined_messages_formatter_type=MessagesFormatterType.MISTRAL)
52+
53+
final_agent = LlamaCppAgent(provider, name="SynthesisAgent", debug_output=True, system_prompt="""
54+
You are a highly intelligent meta-agent responsible for synthesizing information from multiple expert sources. Your critical role involves:
55+
1. Analyzing and integrating responses from various specialized agents to provide a comprehensive, multi-disciplinary answer.
56+
2. Identifying connections, patterns, and relationships between different fields of knowledge.
57+
3. Resolving any contradictions or discrepancies in the information provided by different agents.
58+
4. Providing a balanced perspective that considers input from all relevant domains.
59+
5. Summarizing complex information in a clear, concise, and accessible manner without losing important nuances.
60+
6. Identifying areas where further clarification or information might be needed.
61+
7. Ensuring that the final response addresses all aspects of the original question comprehensively.
62+
Your goal is to create a coherent, well-rounded response that leverages the strengths of each specialized agent while compensating for any individual limitations. Always strive for accuracy, clarity, and depth in your synthesized responses.
63+
""".strip(), predefined_messages_formatter_type=MessagesFormatterType.MISTRAL)
64+
65+
# Create the mixture of agents
66+
mixture = MixtureOfAgents([agent1, agent2, agent3], final_agent)
67+
68+
# Get a response from the mixture
69+
input_message = "What were the mathematical and scientific advancements during the Renaissance period?"
70+
response = mixture.get_response(input_message)
71+
72+
print(response)

src/llama_cpp_agent/messages_formatter.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class MessagesFormatterType(Enum):
2626
PHI_3 = 13
2727
OPEN_INTERPRETER = 14
2828
AUTOCODER = 15
29+
GEMMA_2 = 16
2930

3031
@dataclass
3132
class PromptMarkers:
@@ -176,7 +177,12 @@ def _format_response(
176177
Roles.assistant: PromptMarkers("""### Assistant:\n""", """\n"""),
177178
Roles.tool: PromptMarkers("", ""),
178179
}
179-
180+
gemma_2_prompt_markers = {
181+
Roles.system: PromptMarkers("""""", """\n\n"""),
182+
Roles.user: PromptMarkers("""<start_of_turn>user\n""", """<end_of_turn>\n"""),
183+
Roles.assistant: PromptMarkers("""<start_of_turn>model\n""", """<end_of_turn>\n"""),
184+
Roles.tool: PromptMarkers("", ""),
185+
}
180186
code_ds_prompt_markers = {
181187
Roles.system: PromptMarkers("", """\n\n"""),
182188
Roles.user: PromptMarkers("""@@ Instruction\n""", """\n\n"""),
@@ -352,6 +358,7 @@ def _format_response(
352358
eos_token="<|EOT|>",
353359
)
354360

361+
gemma_2_chat_formatter = MessagesFormatter("", gemma_2_prompt_markers, True, ["<end_of_turn>", "<start_of_turn>"])
355362
predefined_formatter = {
356363
MessagesFormatterType.MISTRAL: mixtral_formatter,
357364
MessagesFormatterType.CHATML: chatml_formatter,
@@ -368,6 +375,7 @@ def _format_response(
368375
MessagesFormatterType.PHI_3: phi_3_chat_formatter,
369376
MessagesFormatterType.OPEN_INTERPRETER: open_interpreter_chat_formatter,
370377
MessagesFormatterType.AUTOCODER: autocoder_chat_formatter,
378+
MessagesFormatterType.GEMMA_2: gemma_2_chat_formatter
371379
}
372380

373381

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from typing import List, Any
2+
from .llm_agent import LlamaCppAgent
3+
4+
5+
class MixtureOfAgents:
6+
def __init__(self, agents: List[LlamaCppAgent], final_agent: LlamaCppAgent):
7+
self.agents = agents
8+
self.final_agent = final_agent
9+
10+
def get_response(self, input_message: str, **kwargs) -> Any:
11+
# Collect responses from all agents
12+
agent_responses = []
13+
for i, agent in enumerate(self.agents):
14+
response = agent.get_chat_response(message=input_message, **kwargs)
15+
agent_responses.append(f"Agent {i + 1} response: {response}")
16+
17+
# Combine all responses into a single message for the final agent
18+
combined_responses = "\n\n".join(agent_responses)
19+
final_prompt = f"""You are a meta-agent tasked with analyzing and synthesizing responses from multiple AI agents to produce a final, comprehensive answer.
20+
21+
Here are the responses from various agents to the following input: "{input_message}"
22+
23+
{combined_responses}
24+
25+
Please analyze these responses, identify key insights, reconcile any contradictions, and compose a final answer that incorporates the best elements from each response while adding your own insights. Your goal is to provide the most accurate, comprehensive, and useful response possible.
26+
27+
Your final answer:"""
28+
29+
# Get the final response from the final agent
30+
final_response = self.final_agent.get_chat_response(message=final_prompt, prompt_suffix="\nMy final answer:", **kwargs)
31+
32+
return final_response
33+
34+
def add_agent(self, agent: LlamaCppAgent):
35+
self.agents.append(agent)
36+
37+
def remove_agent(self, index: int):
38+
if 0 <= index < len(self.agents):
39+
del self.agents[index]
40+
else:
41+
raise IndexError("Agent index out of range")
42+
43+
def set_final_agent(self, agent: LlamaCppAgent):
44+
self.final_agent = agent

0 commit comments

Comments
 (0)