Building AI agents, atomically
docs: improve quickstart guide
KennyVaneetvelde7d31b279179d
diff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.mdindex 215574d..e4b9a34 100644--- a/docs/guides/quickstart.md+++ b/docs/guides/quickstart.md@@ -69,11 +69,12 @@ For a more interactive experience, you can use streaming:import osimport instructorimport openai+import asynciofrom rich.console import Consolefrom rich.live import Livefrom rich.text import Textfrom atomic_agents.lib.components.agent_memory import AgentMemory-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchema# Initialize console for pretty outputsconsole = Console()@@ -81,8 +82,12 @@ console = Console()# Memory setupmemory = AgentMemory()-# OpenAI client setup using the Instructor library-client = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")))+# Initialize memory with an initial message from the assistant+initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")+memory.add_message("assistant", initial_message)++# OpenAI client setup using the Instructor library for async operations+client = instructor.from_openai(openai.AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")))# Agent setup with specified configurationagent = BaseAgent(@@ -93,24 +98,33 @@ agent = BaseAgent())-# Start a loop to handle user inputs and agent responses with streaming-while True:- # Prompt the user for input- user_input = console.input("[bold blue]You:[/bold blue] ")- # Check if the user wants to exit the chat- if user_input.lower() in ["/exit", "/quit"]:- console.print("Exiting chat...")- break-- # Process the user's input through the agent with streaming- input_schema = BaseAgentInputSchema(chat_message=user_input)-- # Stream the response- with Live(console=console, refresh_per_second=4) as live:- response_text = ""- for chunk in agent.stream(input_schema):- response_text += chunk- live.update(Text(f"Agent: {response_text}"))+async def main():+ # Start a loop to handle user inputs and agent responses with streaming+ while True:+ # Prompt the user for input+ user_input = console.input("[bold blue]You:[/bold blue] ")+ # Check if the user wants to exit the chat+ if user_input.lower() in ["/exit", "/quit"]:+ console.print("Exiting chat...")+ break++ # Process the user's input through the agent with streaming+ input_schema = BaseAgentInputSchema(chat_message=user_input)++ # Stream the response+ with Live("", refresh_per_second=10, auto_refresh=True) as live:+ current_response = ""+ async for partial_response in agent.run_async(input_schema):+ if hasattr(partial_response, "chat_message") and partial_response.chat_message:+ # Only update if we have new content+ if partial_response.chat_message != current_response:+ current_response = partial_response.chat_message+ # Display the response+ display_text = Text.assemble(("Agent: ", "bold green"), (current_response, "green"))+ live.update(display_text)++if __name__ == "__main__":+ asyncio.run(main())```## Custom Chatbot@@ -208,66 +222,148 @@ This pattern is especially useful for:For more structured interactions, define custom schemas:```python-from pydantic import BaseModel, Field+import os+import instructor+import openai+from rich.console import Console+from typing import List+from pydantic import Field+from atomic_agents.lib.components.system_prompt_generator import SystemPromptGenerator+from atomic_agents.lib.components.agent_memory import AgentMemory+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema+from atomic_agents.lib.base.base_io_schema import BaseIOSchema++# Initialize console for pretty outputs+console = Console()++# Memory setup+memory = AgentMemory()++# Custom output schema+class CustomOutputSchema(BaseIOSchema):+ """This schema represents the response generated by the chat agent, including suggested follow-up questions."""++ chat_message: str = Field(+ ...,+ description="The chat message exchanged between the user and the chat agent.",+ )+ suggested_user_questions: List[str] = Field(+ ...,+ description="A list of suggested follow-up questions the user could ask the agent.",+ )++# Initialize memory with an initial message from the assistant+initial_message = CustomOutputSchema(+ chat_message="Hello! How can I assist you today?",+ suggested_user_questions=["What can you do?", "Tell me a joke", "Tell me about how you were made"],+)+memory.add_message("assistant", initial_message)-class CustomInput(BaseModel):- question: str = Field(..., description="The user's question")- context: str = Field(..., description="Additional context for the question")+# OpenAI client setup using the Instructor library+client = instructor.from_openai(openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")))-class CustomOutput(BaseModel):- answer: str = Field(..., description="The answer to the user's question")- confidence: float = Field(..., description="Confidence score (0-1)")- sources: list[str] = Field(default_factory=list, description="Sources used")+# Custom system prompt+system_prompt_generator = SystemPromptGenerator(+ background=[+ "This assistant is a knowledgeable AI designed to be helpful, friendly, and informative.",+ "It has a wide range of knowledge on various topics and can engage in diverse conversations.",+ ],+ steps=[+ "Analyze the user's input to understand the context and intent.",+ "Formulate a relevant and informative response based on the assistant's knowledge.",+ "Generate 3 suggested follow-up questions for the user to explore the topic further.",+ ],+ output_instructions=[+ "Provide clear, concise, and accurate information in response to user queries.",+ "Maintain a friendly and professional tone throughout the conversation.",+ "Conclude each response with 3 relevant suggested questions for the user.",+ ],+)-# Create agent with custom schema-agent = BaseAgent[CustomInput, CustomOutput](+# Agent setup with specified configuration and custom output schema+agent = BaseAgent(config=BaseAgentConfig(client=client,model="gpt-4o-mini",- input_schema=CustomInput,- output_schema=CustomOutput+ system_prompt_generator=system_prompt_generator,+ memory=memory,+ output_schema=CustomOutputSchema,))-# Use with custom schema-result = agent.run(- memory=memory,- input_data=CustomInput(- question="What is machine learning?",- context="Explain for a beginner"- )-)-print(f"Answer: {result.answer}")-print(f"Confidence: {result.confidence}")-print(f"Sources: {result.sources}")-```+# Start a loop to handle user inputs and agent responses+while True:+ # Prompt the user for input+ user_input = console.input("[bold blue]You:[/bold blue] ")+ # Check if the user wants to exit the chat+ if user_input.lower() in ["/exit", "/quit"]:+ console.print("Exiting chat...")+ break++ # Process the user's input through the agent+ input_schema = BaseAgentInputSchema(chat_message=user_input)+ response = agent.run(input_schema)++ # Display the agent's response+ console.print("[bold green]Agent:[/bold green] ", response.chat_message)++ # Display the suggested questions+ console.print("\n[bold cyan]Suggested questions you could ask:[/bold cyan]")+ for i, question in enumerate(response.suggested_user_questions, 1):+ console.print(f"[cyan]{i}. {question}[/cyan]")+ console.print() # Add an empty line for better readability-## Multiple Provider Supports+## Multiple Provider SupportThe framework supports multiple AI providers:+```json+{+ "openai": "gpt-4o-mini",+ "anthropic": "claude-3-5-haiku-20241022",+ "groq": "mixtral-8x7b-32768",+ "ollama": "llama3",+ "gemini": "gemini-2.0-flash-exp",+ "openrouter": "mistral/ministral-8b"+}+```++Here's how to set up clients for different providers:+```pythonimport osimport instructorfrom rich.console import Console+from rich.text import Text+from atomic_agents.lib.components.agent_memory import AgentMemory+from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfig, BaseAgentInputSchema, BaseAgentOutputSchemafrom dotenv import load_dotenv-from atomic_agents.agents.base_agent import BaseAgent, BaseAgentConfigload_dotenv()++# Initialize console for pretty outputsconsole = Console()+# Memory setup+memory = AgentMemory()++# Initialize memory with an initial message from the assistant+initial_message = BaseAgentOutputSchema(chat_message="Hello! How can I assist you today?")+memory.add_message("assistant", initial_message)++# Function to set up the client based on the chosen providerdef setup_client(provider):if provider == "openai":from openai import OpenAIapi_key = os.getenv("OPENAI_API_KEY")client = instructor.from_openai(OpenAI(api_key=api_key))- model = "gpt-4-turbo"+ model = "gpt-4o-mini"elif provider == "anthropic":from anthropic import Anthropicapi_key = os.getenv("ANTHROPIC_API_KEY")client = instructor.from_anthropic(Anthropic(api_key=api_key))- model = "claude-3-opus"+ model = "claude-3-5-haiku-20241022"elif provider == "groq":from groq import Groq@@ -276,16 +372,18 @@ def setup_client(provider):Groq(api_key=api_key),mode=instructor.Mode.JSON)- model = "llama3-70b-8192"+ model = "mixtral-8x7b-32768"elif provider == "ollama":from openai import OpenAI as OllamaClientclient = instructor.from_openai(OllamaClient(base_url="http://localhost:11434/v1",- )+ api_key="ollama"+ ),+ mode=instructor.Mode.JSON)- model = "llama3:latest"+ model = "llama3"elif provider == "gemini":from openai import OpenAI@@ -297,23 +395,38 @@ def setup_client(provider):),mode=instructor.Mode.JSON)- model = "gemini-pro"+ model = "gemini-2.0-flash-exp"++ elif provider == "openrouter":+ from openai import OpenAI as OpenRouterClient+ api_key = os.getenv("OPENROUTER_API_KEY")+ client = instructor.from_openai(+ OpenRouterClient(+ base_url="https://openrouter.ai/api/v1",+ api_key=api_key+ )+ )+ model = "mistral/ministral-8b"else:raise ValueError(f"Unsupported provider: {provider}")return client, model-# Model configuration-model_config = BaseAgentConfig(- client=instructor.from_openai(openai.OpenAI()),- model="gpt-4o-mini",- model_api_parameters={"top_p": 0.8, "temperature": 0.7}-)+# Prompt for provider choice+provider = console.input("Choose a provider (openai/anthropic/groq/ollama/gemini/openrouter): ").lower()++# Set up client and model+client, model = setup_client(provider)# Create agent with chosen provideragent = BaseAgent(- config=model_config+ config=BaseAgentConfig(+ client=client,+ model=model,+ memory=memory,+ model_api_parameters={"max_tokens": 2048}+ ))```@@ -339,6 +452,9 @@ export GROQ_API_KEY="your-groq-key"# Geminiexport GEMINI_API_KEY="your-gemini-key"++# OpenRouter+export OPENROUTER_API_KEY="your-openrouter-key"```## Running the Examples