### Redirect Root Path to Getting Started
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/overrides/main.html
A JavaScript IIFE that checks if the current browser path is the root directory and automatically redirects the user to the 'getting-started' documentation page.
```javascript
(function() { var path = window.location.pathname; var basePath = '/sgr-agent-core'; if (path === '/' || path === basePath || path === basePath + '/') { window.location.replace(basePath + '/getting-started/'); } })();
```
--------------------------------
### Setup and Run SGR Agent Benchmark
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/benchmark/simpleqa_benchmark_results.md
Instructions for setting up the environment and running the benchmark test for the SGR Agent Core. This involves installing dependencies, configuring environment variables, and executing the main benchmark script with specified parameters.
```bash
cd benchmark
pip install -r requirements.txt
cp env.example .env # fill env
```
```bash
python run_simpleqa_benchmark.py \
--path_to_simpleqa ./data/simpleqa_verified.csv \
--output_path ./simpleqa_bench_results.xlsx \
--batch_size 10
```
--------------------------------
### Install Development Dependencies
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/sgr-api/SGR-Quick-Start.md
Commands to install UV for backend management and verify Node.js/npm versions for frontend development.
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
node --version
npm --version
```
--------------------------------
### Install and Configure SGR Agent Core
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_file_agent/README.md
Commands to install the core package and initialize the configuration file for the agent.
```bash
pip install sgr-agent-core
cp config.yaml.example config.yaml
```
--------------------------------
### Install and Configure SGR Agent Core
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_deep_research/README.md
Commands to install the core package and prepare the configuration file for API keys.
```bash
pip install sgr-agent-core
cp config.yaml my_config.yaml
```
--------------------------------
### Running SGR Agent Core as a Python Library
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/README.md
Instructions for installing and running the SGR Agent Core as a Python library, including starting the API server.
```bash
# Install the library
pip install sgr-agent-core
# Run the API server with a custom config file
sgr --config-file examples/sgr_deep_research/config.yaml
# or use short option
sgr -c examples/sgr_deep_research/config.yaml
# Alternatively, run directly with Python
python -m sgr_agent_core.server --config-file examples/sgr_deep_research/config.yaml
```
--------------------------------
### Installing SGR Agent Core Library
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/README.md
Instructions for installing the SGR Agent Core framework as a Python library via pip.
```bash
pip install sgr-agent-core
```
--------------------------------
### Run Backend and Frontend Services
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/sgr-api/SGR-Quick-Start.md
Commands to synchronize dependencies and start the backend Python server and the frontend development server.
```bash
uv sync
uv run python sgr_agent_core
cd sgr-deep-research-frontend
npm install
npm run dev
```
--------------------------------
### Configuration Example: simple_search_agent
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/first-steps.md
This JSON output represents the detailed configuration for the `simple_search_agent`, including LLM settings, execution parameters, prompt configurations, and the specific tools it utilizes.
```json
{
"llm": {
"api_key": "***",
"base_url": "***",
"model": "gpt-4.1-mini",
"max_tokens": 2000,
"temperature": 0.2,
"proxy": null
},
"execution": {
"max_clarifications": 3,
"max_iterations": 7,
"mcp_context_limit": 15000,
"logs_dir": "logs",
"reports_dir": "reports"
},
"prompts": {
"system_prompt_file": "sgr_agent_core\\prompts\\system_prompt.txt",
"initial_user_request_file": "sgr_agent_core\\prompts\\initial_user_request.txt",
"clarification_response_file": "sgr_agent_core\\prompts\\clarification_response.txt",
"system_prompt_str": null,
"initial_user_request_str": null,
"clarification_response_str": null,
"system_prompt": "\nYou are an expert researcher with adaptive planning and schema-guided-reasoning capabilities. You get the research task and you neeed to do research and genrete answer\n\n\n\nPAY ATTENTION TO THE DATE INSIDE THE USER REQUEST\nDATE FORMAT: YYYY-MM-DD HH:MM:SS (ISO 8601)...",
"initial_user_request": "Current Date: {current_date} (Year-Month-Day ISO format: YYYY-MM-DD HH:MM:SS)\nORIGINAL USER REQUEST:\n\n{task}\n",
"clarification_response": "Current Date: {current_date} (Year-Month-Day ISO format: YYYY-MM-DD HH:MM:SS)\n\nCLARIFICATIONS:\n\n{clarifications}\n"
},
"mcp": {
"mcpServers": {}
},
"name": "simple_search_agent",
"base_class": "ResearchSGRToolCallingAgent",
"tools": [
{"name": "web_search_tool", "tavily_api_key": "***", "max_results": 5, "content_limit": 5000},
{"name": "final_answer_tool"}
]
}
```
--------------------------------
### Agent Reasoning Log Example
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/first-steps.md
Provides an example of an agent's reasoning log, illustrating the step-by-step process the agent follows to complete a task. It includes details about the LLM's thought process, tool execution, and the overall plan status.
```Log
INFO:sgr_agent_core.agents.sgr_tool_calling_agent_923e6191-b3a9-4ef1-b4af-c1a2c587e512:🚀 Starting for task: 'Write a forecast of the main trends in the development of artificial intelligence'
INFO:sgr_agent_core.agents.sgr_tool_calling_agent_923e6191-b3a9-4ef1-b4af-c1a2c587e512:Step 1 started
INFO:sgr_agent_core.agents.sgr_tool_calling_agent_923e6191-b3a9-4ef1-b4af-c1a2c587e512:
###############################################
🤖 LLM RESPONSE DEBUG:
🧠 Reasoning Steps: ['Identify the key trends in artificial intelligence development up to 2025.', 'Analyze the potential future directions based on current advancements and research.', 'Compile a comprehensive forecast based on the identified trends.']
📊 Current Situation: 'Research on artificial intelligence trends has been conducted, focusing on advancements, challenges, and future directions. Key areas include machine learning, natural language processing, and ethical considerations....'
📋 Plan Status: 'Research plan is in progress, focusing on compiling trends and forecasts....'
🔍 Searches Done: 0
🔍 Clarifications Done: 0
✅ Enough Data: False
📝 Remaining Steps: ['Gather data on recent AI advancements and trends from 2023 to 2025.', 'Analyze the implications of these trends for future AI development.', 'Draft the forecast report based on the findings.']
🏁 Task Completed: False
➡️ Next Step: Gather data on recent AI advancements and trends from 2023 to 2025.
###############################################
INFO:sgr_agent_core.agents.sgr_tool_calling_agent_923e6191-b3a9-4ef1-b4af-c1a2c587e512:
###############################################
🛠️ TOOL EXECUTION DEBUG:
🔧 Tool Name: generateplantool
📋 Tool Model: {
"reasoning": "To provide a comprehensive forecast on the development of artificial intelligence, it is essential to gather data on recent advancements and analyze the implications of these trends. This will help in identifying key areas of growth and potential challenges in the field.",
"research_goal": "Forecast the main trends in the development of artificial intelligence up to 2025 and beyond.",
"planned_steps": [
"Gather data on AI advancements from 2023 to 2025, focusing on machine learning, natural language processing, and ethical considerations.",
"Analyze the implications of these trends for future AI development, including potential applications and societal impact.",
"Draft a comprehensive forecast report based on the findings."
],
"search_strategies": [
"Conduct literature review on AI trends from 2023 to 2025.",
"Analyze industry reports and expert opinions on the future of AI."
]
}
🔍 Result: '{
"research_goal": "Forecast the main trends in the development of artificial intelligence up to 2025 and beyond.",
"planned_steps": [
"Gather data on AI advancements from 2023 to 2025, focusing on machine learning, natural language processing, and ethical considerations.",
```
--------------------------------
### Full Agent Customization
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
An example demonstrating comprehensive overrides for LLM settings, execution parameters, and a full suite of tools.
```yaml
tools:
web_search_tool:
engine: "tavily"
api_key: "your-tavily-api-key"
max_results: 15
max_searches: 6
extract_page_content_tool:
tavily_api_key: "your-tavily-api-key"
content_limit: 2000
agents:
custom_research_agent:
base_class: "examples.sgr_deep_research.agents.ResearchSGRAgent"
llm:
model: "gpt-4o"
temperature: 0.3
max_tokens: 16000
execution:
max_iterations: 15
max_clarifications: 5
streaming_generator: "openai"
logs_dir: "logs/custom_agent"
reports_dir: "reports/custom_agent"
tools:
- "web_search_tool"
- "extract_page_content_tool"
- "create_report_tool"
- "clarification_tool"
- "generate_plan_tool"
- "adapt_plan_tool"
- "final_answer_tool"
```
--------------------------------
### Configuration Example: writer_agent
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/first-steps.md
This JSON output displays the configuration for the `writer_agent`, detailing its LLM parameters, execution settings, and prompt configurations, including a specific system prompt for writing tasks.
```json
{
"llm": {
"api_key": "***",
"base_url": "***",
"model": "gpt-4o",
"max_tokens": 2000,
"temperature": 0.8,
"proxy": null
},
"execution": {
"max_clarifications": 3,
"max_iterations": 7,
"mcp_context_limit": 15000,
"logs_dir": "logs",
"reports_dir": "reports"
},
"prompts": {
"system_prompt_file": "sgr_agent_core\\prompts\\system_prompt.txt",
"initial_user_request_file": "sgr_agent_core\\prompts\\initial_user_request.txt",
"clarification_response_file": "sgr_agent_core\\prompts\\clarification_response.txt"
}
}
```
--------------------------------
### Configure RunCommandTool for Safe Mode
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/tools/run-command.md
Example configuration for running the tool in safe mode, which utilizes Bubblewrap for Linux namespace isolation. This requires bwrap to be installed on the host system.
```yaml
tools:
run_command_tool:
workspace_path: "/tmp/agent_workspace"
mode: "safe"
timeout_seconds: 60
```
--------------------------------
### Start SGR Agent Core Server
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/research_with_images/README.md
Command to initialize the SGR Agent Core API server using a specific configuration file.
```bash
sgr --config-file examples/sgr_deep_research/config.yaml
```
--------------------------------
### Creating a Custom Agent
Source: https://context7.com/vamplabai/sgr-agent-core/llms.txt
This example demonstrates how to create a custom agent by extending the `BaseAgent` class and implementing the reasoning, action selection, and action phases.
```APIDOC
## Creating a Custom Agent
Extend BaseAgent to create custom agents with specialized behavior by implementing the reasoning, action selection, and action phases.
```python
from typing import Type
from openai import AsyncOpenAI
from sgr_agent_core import BaseAgent, BaseTool, AgentConfig, ReasoningTool
class CustomResearchAgent(BaseAgent):
"""Custom agent with specialized research workflow."""
name: str = "custom_research_agent"
def __init__(
self,
task_messages: list,
openai_client: AsyncOpenAI,
agent_config: AgentConfig,
toolkit: list[Type[BaseTool]],
def_name: str | None = None,
**kwargs,
):
super().__init__(
task_messages=task_messages,
openai_client=openai_client,
agent_config=agent_config,
toolkit=toolkit,
def_name=def_name,
**kwargs,
)
async def _reasoning_phase(self) -> ReasoningTool:
"""Determine next action based on current context."""
phase_id = f"{self._context.iteration}-reasoning"
async with self.openai_client.chat.completions.stream(
messages=await self._prepare_context(),
tools=await self._prepare_tools(),
**self.config.llm.to_openai_client_kwargs(),
) as stream:
async for event in stream:
if event.type == "chunk":
self.streaming_generator.add_chunk(event.chunk, phase_id)
completion = await stream.get_final_completion()
reasoning = completion.choices[0].message.tool_calls[0].function.parsed_arguments
self._log_reasoning(reasoning)
return reasoning
async def _select_action_phase(self, reasoning: ReasoningTool) -> BaseTool:
"""Select tool based on reasoning output."""
# Custom tool selection logic
tool = reasoning.function # or custom selection
self.streaming_generator.add_tool_call(f"{self._context.iteration}-action", tool)
return tool
async def _action_phase(self, tool: BaseTool) -> str:
"""Execute the selected tool."""
phase_id = f"{self._context.iteration}-action"
result = await tool(
self._context,
self.config,
**self.tool_configs.get(tool.tool_name, {})
)
self.conversation.append({"role": "tool", "content": result, "tool_call_id": phase_id})
self.streaming_generator.add_tool_result(phase_id, result, tool.tool_name)
self._log_tool_execution(tool, result)
return result
# Agent is auto-registered via AgentRegistryMixin
# Use in config: base_class: "custom_research_agent"
```
```
--------------------------------
### Minimal Agent Configuration
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
A basic example showing how to override only the LLM model and specify a minimal toolset for an agent.
```yaml
agents:
simple_agent:
base_class: "SGRToolCallingAgent"
# Override only the model
llm:
model: "gpt-4o-mini"
# Specify minimal toolset
tools:
- "web_search_tool"
- "final_answer_tool"
```
--------------------------------
### Verify SGR Agent Core Installation
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/getting-started/installation.md
Verify the package installation by checking the version and testing the command-line utility availability.
```bash
python -c "import sgr_agent_core; print(sgr_agent_core.__version__)"
sgr --help
sgrsh --help
```
--------------------------------
### Create Agent from Configs and Run (Python)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/highlights.md
Shows how to create an agent using configuration files (config.yaml and agents.yaml) and then execute it. This approach separates agent definition from the execution logic, making it suitable for more complex agent setups managed through external configurations. It utilizes `GlobalConfig` and `AgentFactory` for loading and creating the agent.
```python
from sgr_agent_core import GlobalConfig, AgentFactory
config = GlobalConfig.from_yaml("config.yaml")
config.definitions_from_yaml("agents.yaml")
researcher_def = config.agents["researcher"]
agent = await AgentFactory.create(
researcher_def,
task_messages=[{"role": "user", "content": "Find recent articles on multi-agent systems"}],
)
await agent.execute()
```
--------------------------------
### Using the SGR CLI Tool (sgrsh)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/README.md
Examples of using the `sgrsh` command-line interface for interactive queries and agent selection.
```bash
# Single query mode
sgrsh "Найди цену биткоина"
# With agent selection (e.g. sgr_agent, dialog_agent)
sgrsh --agent sgr_agent "What is AI?"
# With custom config file
sgrsh -c config.yaml -a sgr_agent "Your query"
```
--------------------------------
### OpenAI-compatible API Usage
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_file_agent/README.md
Example of how to interact with the SGR File Agent using an OpenAI-compatible API client.
```APIDOC
## Using OpenAI-compatible API
If you have the SGR Agent Core API service running, you can interact with the file agent using an OpenAI-compatible client.
### Example Code
```python
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:8010/v1",
api_key="dummy",
)
response = client.chat.completions.create(
model="sgr_file_agent",
messages=[
{
"role": "user",
"content": "Find all PDF files in my Downloads folder from last week",
}
],
stream=True,
)
for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
```
### Description
This example shows how to configure the `openai` Python client to connect to the SGR Agent Core API endpoint and send a chat completion request to the `sgr_file_agent` model. It demonstrates streaming the response chunks.
```
--------------------------------
### Python API Usage
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_file_agent/README.md
Example of how to use the SGR File Agent programmatically with Python.
```APIDOC
## Using Python API
This section demonstrates how to integrate and use the SGR File Agent within your Python applications.
### Example Code
```python
import asyncio
from pathlib import Path
from sgr_agent_core.agent_config import GlobalConfig
from sgr_agent_core.agent_factory import AgentFactory
# Load configuration
config_path = Path(__file__).parent / "config.yaml"
config = GlobalConfig.from_yaml(str(config_path))
# Get agent definition
agent_def = config.agents["sgr_file_agent"]
# Create and run agent
async def main():
agent = await AgentFactory.create(
agent_def,
task_messages=[
{"role": "user", "content": "Find all Python files in the project"}
],
)
# working_directory is automatically set from config if specified
print(f"Working directory: {agent.working_directory}")
async for chunk in agent.stream():
print(chunk, end="", flush=True)
result = await agent.execute()
print(f"\n\nFinal result: {result}")
asyncio.run(main())
```
### Description
This Python script loads the SGR File Agent configuration, creates an agent instance with a user task, streams the agent's output, and prints the final result. It highlights how to set up the agent and interact with it asynchronously.
```
--------------------------------
### Restrict Execution with Include and Exclude Paths
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/tools/run-command.md
Example configuration demonstrating how to restrict allowed commands and paths. Include paths take priority over exclude paths, allowing for granular control over the execution environment.
```yaml
tools:
run_command_tool:
workspace_path: "/tmp/agent_workspace"
mode: "unsafe"
timeout_seconds: 60
include_paths:
- "ls"
- "cat"
- "/usr/bin/python3"
- "/tmp/agent_workspace"
exclude_paths:
- "rm"
- "/usr/bin/rm"
```
--------------------------------
### Configure Agent Tools in YAML
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_file_agent/README.md
Example configuration for defining custom tools and mapping them to Python classes within the agent's configuration file.
```yaml
tools:
reasoning_tool:
read_file_tool:
base_class: "tools.ReadFileTool"
custom_tool:
base_class: "examples.sgr_file_agent.tools.CustomTool"
agents:
sgr_file_agent:
tools:
- "reasoning_tool"
- "read_file_tool"
- "find_files_fast_tool"
working_directory: "/path/to/work/dir"
```
--------------------------------
### Using the sgrsh Interactive CLI Tool
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/README.md
Examples of using the sgrsh utility for interactive queries, including specifying agents and custom configuration files.
```bash
sgrsh "Найди цену биткоина"
sgrsh --agent sgr_agent "What is AI?"
sgrsh -c config.yaml -a sgr_agent "Your query"
```
--------------------------------
### Running Open WebUI with SGR Agent (Docker)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/highlights.md
Provides instructions to run Open WebUI using Docker, connecting it to the SGR agent's API. This setup allows for a chat interface with history and agent switching without frontend development.
```bash
docker run -d \
-p 3000:8080 \
-e OPENAI_API_BASE_URL=http://host.docker.internal:8010/v1 \
-e OPENAI_API_KEY=dummy \
ghcr.io/open-webui/open-webui:main
```
--------------------------------
### Open WebUI Integration
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/highlights.md
Instructions on how to integrate the SGR Agent Core with Open WebUI for a user-friendly chat interface. This includes Docker setup and configuration adjustments.
```APIDOC
## Open WebUI Integration
### Description
Connects the SGR Agent Core to Open WebUI, providing a full chat interface with history, agent switching, and streaming capabilities without frontend development.
### Setup
Run Open WebUI using Docker, pointing it to your SGR agent server.
### Docker Command
```bash
docker run -d \
-p 3000:8080 \
-e OPENAI_API_BASE_URL=http://host.docker.internal:8010/v1 \
-e OPENAI_API_KEY=dummy \
ghcr.io/open-webui/open-webui:main
```
### Access
After startup, open `http://localhost:3000` in your browser.
### Configuration
To ensure proper functionality with Open WebUI, you need to switch the streaming adapter in your `config.yaml` file:
```yaml
execution:
streaming_generator: "open_webui" # instead of "openai" (default)
```
```
--------------------------------
### Agent Configuration with ExtractPageContentTool (YAML)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/tools/extract-page-content-tool.md
Example of configuring an agent to use the ExtractPageContentTool alongside the web_search_tool. It demonstrates how to set agent-specific tool lists and override tool configurations like the content_limit.
```yaml
agents:
research_agent:
search:
content_limit: 2000
tools:
- "web_search_tool"
- "extract_page_content_tool"
```
--------------------------------
### Deploy SGR Agent Core with Docker
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/getting-started/index.md
This snippet demonstrates how to run the SGR Agent Core service using Docker. It includes directory setup, configuration, and the command to launch the container with volume mappings.
```bash
git clone https://github.com/vamplabai/sgr-agent-core.git
cd sgr-agent-core
sudo mkdir -p logs reports
sudo chmod 777 logs reports
cp examples/sgr_deep_research/config.yaml.example examples/sgr_deep_research/config.yaml
docker run --rm -i \
--name sgr-agent \
-p 8010:8010 \
-v $(pwd)/examples/sgr_deep_research:/app/examples/sgr_deep_research:ro \
-v $(pwd)/logs:/app/logs \
-v $(pwd)/reports:/app/reports \
ghcr.io/vamplabai/sgr-agent-core:latest \
--config-file /app/examples/sgr_deep_research/config.yaml \
--host 0.0.0.0 \
--port 8010
```
--------------------------------
### Consume Streaming Output from Agent (Python)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/agents.md
Provides a Python example of how to consume streaming output from an agent. This code iterates over the agent's streaming generator, printing each chunk as it is received, which is useful for real-time feedback during agent execution.
```python
async for chunk in agent.streaming_generator.stream():
print(chunk, end="")
```
--------------------------------
### Initialize Configuration Files
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/sgr-api/SGR-Quick-Start.md
Commands to prepare the environment by copying template configuration files and creating necessary agent definition files.
```bash
cp config.yaml.example config.yaml
touch agents.yaml
```
--------------------------------
### Initialize GlobalConfig
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
Demonstrates how to instantiate the GlobalConfig object to manage application settings. Note that GlobalConfig is a singleton, so all instances refer to the same configuration state.
```python
from sgr_agent_core import GlobalConfig
config = GlobalConfig()
```
--------------------------------
### Install SGR Agent Core via pip
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/getting-started/installation.md
Install the core package and its optional dependencies for development, testing, or documentation purposes.
```bash
pip install sgr-agent-core
pip install sgr-agent-core[dev]
pip install sgr-agent-core[tests]
pip install sgr-agent-core[docs]
```
--------------------------------
### Create Agent Directly using Constructor
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/first-steps.md
Demonstrates the conventional method of creating an agent by directly using the class constructor. This approach provides full control over the agent's components, adapters, and tools at startup. It requires setting up agent configuration, an OpenAI client, and a toolkit.
```Python
import asyncio
import logging
from openai import AsyncOpenAI
import sgr_agent_core.tools as tools
from sgr_agent_core import AgentConfig
from sgr_agent_core.agents import SGRToolCallingAgent
logging.basicConfig(level=logging.INFO)
async def main():
agent_config = AgentConfig()
agent_config.llm.api_key = "___" # Or just set in ENV
agent_config.llm.base_url = "___" # Or just set in ENV
openai_client = AsyncOpenAI(api_key=agent_config.llm.api_key,
base_url=agent_config.llm.base_url)
toolkit = [
tools.GeneratePlanTool,
tools.FinalAnswerTool,
]
# Create agent directly
agent = SGRToolCallingAgent(
task_messages=[{"role": "user", "content": "Write a forecast of the main trends in the development of artificial intelligence"}],
openai_client=openai_client,
agent_config=agent_config,
toolkit=toolkit,
)
print(await agent.execute())
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Initialize Agent using AgentDefinition and AgentFactory
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/first-steps.md
Demonstrates how to programmatically define an agent using the AgentDefinition class and instantiate it via the AgentFactory. This approach allows for modular configuration of tools, LLM settings, and base agent classes.
```python
import asyncio
import logging
import sgr_agent_core.tools as tools
from sgr_agent_core import AgentDefinition
from sgr_agent_core import AgentFactory
from sgr_agent_core.agents import SGRToolCallingAgent
logging.basicConfig(level=logging.INFO)
async def main():
agent_def = AgentDefinition(
name="my_research_agent",
base_class=SGRToolCallingAgent,
tools=[
tools.GeneratePlanTool,
tools.FinalAnswerTool,
],
llm={
"api_key": "___",
"base_url": "___",
},
)
agent = await AgentFactory.create(
agent_def=agent_def,
task_messages=[{"role": "user", "content": "Write a forecast of the main trends in the development of artificial intelligence"}],
)
print(await agent.execute())
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### GET /agents
Source: https://github.com/vamplabai/sgr-agent-core/wiki/SGR-Integration-&-Examples
Retrieves a list of all currently active agents in the system.
```APIDOC
## GET /agents
### Description
Fetches a list of all active agents currently managed by the core.
### Method
GET
### Endpoint
/agents
### Response
#### Success Response (200)
- **agents** (array) - List of active agent objects
```
--------------------------------
### GET /v1/models
Source: https://context7.com/vamplabai/sgr-agent-core/llms.txt
Retrieve a list of all available agent definitions configured in the system.
```APIDOC
## GET /v1/models
### Description
Returns a list of all configured agents that can be used as models.
### Method
GET
### Endpoint
/v1/models
### Response
#### Success Response (200)
- **data** (array) - List of available agent models.
```
--------------------------------
### GET /agents/{agent_id}/state
Source: https://github.com/vamplabai/sgr-agent-core/wiki/SGR-Integration-&-Examples
Retrieves the current state of a specific agent.
```APIDOC
## GET /agents/{agent_id}/state
### Description
Returns the internal state of the specified agent.
### Method
GET
### Endpoint
/agents/{agent_id}/state
### Parameters
#### Path Parameters
- **agent_id** (string) - Required - The unique identifier of the agent
### Response
#### Success Response (200)
- **state** (object) - The current state object of the agent
```
--------------------------------
### Agent Deletion Success Response (JSON)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/sgr-api/SGR-Description-API.md
Example of a JSON response indicating successful cancellation and deletion of an agent.
```json
{
"agent_id": "sgr_agent_12345-67890-abcdef",
"deleted": true,
"final_state": "cancelled"
}
```
--------------------------------
### Use Python API to Run Agent
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_deep_research_without_reporting/README.md
Demonstrates how to use the sgr_agent_core Python library to load configuration, create an agent, and execute a task, streaming the results.
```python
import asyncio
from pathlib import Path
from sgr_agent_core.agent_config import GlobalConfig
from sgr_agent_core.agent_factory import AgentFactory
from sgr_agent_core.agent_definition import AgentDefinition
# Load configuration
config_path = Path(__file__).parent / "config.yaml"
GlobalConfig.from_yaml(str(config_path))
# Get agent definition
agent_def = GlobalConfig().agents["sgr_agent_no_reporting"]
# Create and run agent
async def main():
agent = await AgentFactory.create(
agent_def,
task_messages=[{"role": "user", "content": "Research AI trends in 2024"}],
)
async for chunk in agent.stream():
print(chunk, end="", flush=True)
result = await agent.execute()
print(f"\n\nFinal result: {result}")
asyncio.run(main())
```
--------------------------------
### BaseAgent Control Methods
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/agents.md
Describes the primary methods for controlling agent execution, including starting and canceling the agent.
```APIDOC
## BaseAgent Control Methods
### Description
These methods provide the interface for initiating and terminating an agent's execution.
### `execute()` Method
#### Description
Starts the agent's execution process. It creates an asyncio task for the agent's work, stores it for potential cancellation, and then waits for the task to complete.
#### Signature
```python
async def execute(self) -> str | None:
```
### `cancel()` Method
#### Description
Allows for the cancellation of a currently running agent execution. If an execution task is active, it is cancelled, and the agent's state is updated to `CANCELLED`.
#### Signature
```python
async def cancel(self) -> None:
```
### Note on Agent Cancellation
When an agent is cancelled using the `cancel()` method, its state is set to `CANCELLED`, which is considered a terminal state and included in `FINISH_STATES`.
```
--------------------------------
### Configure API Keys
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_deep_research_without_reporting/README.md
Copies the default configuration file and instructs on setting necessary API keys for OpenAI and Tavily.
```bash
cp config.yaml my_config.yaml
```
--------------------------------
### Agent Control Methods
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/agents.md
Methods for managing the lifecycle of an agent, specifically starting execution and cancelling running tasks.
```python
async def execute(self) -> str | None:
"""Start agent execution and return the result."""
async def cancel(self) -> None:
"""Cancel the agent execution."""
```
--------------------------------
### Create and Run an Agent Directly (Python)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/highlights.md
Demonstrates how to instantiate and execute an SGR Agent directly in Python code. It initializes the agent with task messages, an OpenAI client, agent configuration, and a toolkit, then runs the agent and prints the result. This is useful for quick testing and integration within Python applications.
```python
import asyncio
from openai import AsyncOpenAI
from sgr_agent_core import AgentConfig
from sgr_agent_core.agents.sgr_agent import SGRAgent
from sgr_agent_core.tools.final_answer_tool import FinalAnswerTool
async def main() -> None:
client = AsyncOpenAI(api_key="YOUR_OPENAI_API_KEY")
agent = SGRAgent(
task_messages=[
{"role": "user", "content": "Give a brief overview of RAG systems"},
],
openai_client=client,
agent_config=AgentConfig(),
toolkit=[FinalAnswerTool],
)
result = await agent.execute()
print(result)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Load Configuration from YAML
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
Shows how to load structured configuration settings from a YAML file into the GlobalConfig instance.
```python
from sgr_agent_core import GlobalConfig
# Load from config.yaml
config = GlobalConfig.from_yaml("config.yaml")
```
--------------------------------
### Initialize and Run Agent in Python
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/getting-started/index.md
This snippet shows how to define an agent using the AgentFactory and execute a task programmatically. It requires an OpenAI-compatible LLM configuration.
```python
import asyncio
from sgr_agent_core import AgentDefinition, AgentFactory
from sgr_agent_core.agents import SGRToolCallingAgent
import sgr_agent_core.tools as tools
async def main():
agent_def = AgentDefinition(
name="my_agent",
base_class=SGRToolCallingAgent,
tools=[tools.GeneratePlanTool, tools.FinalAnswerTool],
llm={
"api_key": "your-api-key",
"base_url": "https://api.openai.com/v1",
},
)
agent = await AgentFactory.create(
agent_def=agent_def,
task_messages=[{"role": "user", "content": "Research AI trends"}],
)
result = await agent.execute()
print(result)
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Agent Not Waiting for Clarification Error Response (JSON)
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/sgr-api/SGR-Description-API.md
Example of a JSON response when attempting to provide clarification to an agent that is not in the 'waiting_for_clarification' state.
```json
{
"detail": "Agent is not waiting for clarification"
}
```
--------------------------------
### Configure Agent Base Class Imports
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/examples/sgr_deep_research/README.md
Examples of using relative versus absolute paths for the base_class field in agent configuration files.
```yaml
agents:
sgr_agent:
base_class: "agents.ResearchSGRAgent"
# Absolute path alternative
# base_class: "examples.sgr_deep_research.agents.ResearchSGRAgent"
```
--------------------------------
### Use CLI Interactive Shell (sgrsh)
Source: https://context7.com/vamplabai/sgr-agent-core/llms.txt
Demonstrates how to use the sgrsh command-line tool for single queries or interactive chat sessions, including options for specifying agents and custom configuration files.
```bash
sgrsh "Find the current Bitcoin price"
sgrsh --agent sgr_agent "What are the latest AI research trends?"
sgrsh -c examples/sgr_deep_research/config.yaml -a dialog_agent "Explain quantum computing"
sgrsh
```
--------------------------------
### Configure Custom Tools in YAML
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/tools.md
Demonstrates two methods for integrating custom tools into the agent configuration: direct reference for pre-registered tools and explicit definition using base_class paths.
```yaml
agents:
my_agent:
base_class: "SGRToolCallingAgent"
tools:
- "custom_tool"
- "web_search_tool"
tools:
custom_tool:
base_class: "tools.CustomTool"
```
--------------------------------
### Orchestrate SGR Agent Core with Docker Compose
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/getting-started/installation.md
Configuration and command to deploy the agent core using Docker Compose for a complete service setup.
```yaml
services:
backend:
build:
context: .
dockerfile: Dockerfile
command:
- --config-file=/app/config.yaml
- --agents-file=/app/agents.yaml
ports:
- "8010:8010"
volumes:
- ./config.yaml:/app/config.yaml:ro
- ./agents.yaml:/app/agents.yaml:ro
environment:
- SGR__LLM__API_KEY=your-api-key
- SGR__LLM__BASE_URL=https://api.openai.com/v1
```
```bash
cp docker-compose.dist.yaml docker-compose.yaml
docker-compose up -d
```
--------------------------------
### Configure Agent Tools and Overrides
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
Demonstrates how to assign tools to an agent and perform per-tool configuration overrides within an agent definition.
```yaml
agents:
my_agent:
base_class: "SGRToolCallingAgent"
tools:
- "web_search_tool"
- "reasoning_tool"
- extract_page_content_tool:
content_limit: 2000
- web_search_tool:
max_results: 15
max_searches: 6
```
--------------------------------
### Agent with Custom Tool Definitions
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
Demonstrates how to define custom tools in the configuration and reference them within an agent's toolset.
```yaml
tools:
reasoning_tool:
custom_file_tool:
base_class: "tools.CustomFileTool"
agents:
file_agent:
base_class: "SGRToolCallingAgent"
llm:
model: "gpt-4o-mini"
tools:
- "reasoning_tool"
- "custom_file_tool"
- "final_answer_tool"
```
--------------------------------
### Configure RunCommandTool for Unsafe Mode
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/tools/run-command.md
Example configuration for running the tool in unsafe mode, which uses local subprocesses. This is suitable for cross-platform use where namespace isolation is not required.
```yaml
tools:
run_command_tool:
workspace_path: "/tmp/agent_workspace"
mode: "unsafe"
timeout_seconds: 120
```
--------------------------------
### Programmatic Agent Configuration Loading
Source: https://github.com/vamplabai/sgr-agent-core/blob/main/docs/en/framework/configuration.md
Demonstrates how to initialize the GlobalConfig object and load agent definitions from multiple YAML files using the Python API.
```python
from sgr_agent_core import GlobalConfig
config = GlobalConfig.from_yaml("config.yaml")
config.definitions_from_yaml("agents.yaml")
config.definitions_from_yaml("more_agents.yaml")
```