ai-agent-book 精选快照(<2MB 代码与文档,来自 github.com/bojieli/ai-agent-book)
Build latest book artifacts / build (push) Canceled after 0s
dependency resolution / resolve (3.11) (push) Canceled after 0s
dependency resolution / resolve (3.13) (push) Canceled after 0s
deploy-pages / build (push) Canceled after 0s
deploy-pages / deploy (push) Canceled after 0s
i18n consistency check / check (push) Canceled after 0s
provider adoption tests / test (chapter2/context-compression) (push) Canceled after 0s
provider adoption tests / test (chapter2/prompt-injection) (push) Canceled after 0s
provider adoption tests / test (chapter2/system-hint) (push) Canceled after 0s
provider adoption tests / test (chapter3/log-sanitization) (push) Canceled after 0s
web-search-agent tests / test (push) Canceled after 0s
web-search-agent tests / agentbook (push) Canceled after 0s

This commit is contained in:
2026-08-20 13:12:50 +00:00
commit b119135836
10275 changed files with 3284984 additions and 0 deletions
@@ -0,0 +1,9 @@
from aworld.prompt.base import (
Prompt,
create_prompt,
)
__all__ = [
"Prompt",
"create_prompt",
]
@@ -0,0 +1,131 @@
import logging
import re
from typing import Dict, Any, Optional, Callable, List
from aworld.core.context.base import Context
from aworld.core.context.prompts.dynamic_variables import create_simple_field_getter, create_multiple_field_getters, \
get_field_values_from_list
# Import system_prompt directly from the module
try:
from aworld.prompt.templates.prompt import system_prompt as default_system_prompt
except ImportError:
default_system_prompt = ""
class Prompt:
"""
Prompt processing class, responsible for loading templates and rendering variables
"""
def __init__(self, template: str = None, context: Context = None) -> None:
"""
Initialize Prompt class
Args:
template: Template content. If None, will load default system prompt.
"""
if template is None:
self.template_content = default_system_prompt
else:
self.template_content = template
# Extract variables from the template
self.prompt_variables = self._extract_variables(self.template_content)
self.context = context
def _extract_variables(self, template_content: str) -> List[str]:
"""
Extract variables from the template
Args:
template_content: Template content
Returns:
List of variables
"""
# Use regular expression to extract {{variable}} format variables
pattern = r'\{\{([a-zA-Z0-9_]+)\}\}'
if not template_content:
return []
try:
matches = re.findall(pattern, template_content)
# Remove duplicates
return list(set(matches))
except Exception as e:
logging.warning(f"Error extracting variables from template: {str(e)}")
return []
def _get_variable_values_from_api(self, variables: List[str]) -> Dict[str, Any]:
"""
Get variable values from API
Args:
variables: List of variables
Returns:
Dictionary of variable values, key is variable name, value is variable value
"""
# This is a mock implementation, should be replaced with actual API calls in real use
result = {}
context = self.context
#getter = create_multiple_field_getters(variables, context)
if context and variables:
field_paths = variables
try:
result = get_field_values_from_list(context=context, field_paths=field_paths,default="")
except Exception as e:
logging.warning(f"Error getting variable values from API: {str(e)}")
return None
return result
def get_prompt(self, variables: Dict[str, Any] = None, variable_resolver: Optional[Callable[[List[str]], Dict[str, Any]]] = None) -> str:
"""
Render template, replace variables
Args:
variables: Optional variable dictionary, if provided, will override API values
variable_resolver: Optional variable resolver function, used to get variable values, higher priority than built-in API method
Returns:
Rendered content
"""
if variables is None:
variables = {}
# Get variable values
if variable_resolver:
# If custom variable resolver is provided, use it
resolved_variables = variable_resolver(self.prompt_variables)
else:
# Otherwise use the built-in API method
resolved_variables = self._get_variable_values_from_api(self.prompt_variables)
# Override API values with provided variables
for var_name, var_value in variables.items():
if var_value is not None: # Only override when value is not None
resolved_variables[var_name] = var_value
# Render template
rendered_content = self.template_content
# Replace variables
for var_name, var_value in resolved_variables.items():
if var_value:
placeholder = f"{{{{{var_name}}}}}"
rendered_content = rendered_content.replace(placeholder, str(var_value))
return rendered_content
# Simplified API, only keep the prompt creation functionality
def create_prompt(template_content: str) -> Prompt:
"""
Create Prompt from string
Args:
template_content: Template content
Returns:
Prompt object
"""
return Prompt(template_content)
@@ -0,0 +1,56 @@
system_prompt="""
<system_instruction>
You are an advanced AI assistant powered by a large language model, operating within the AWorld framework. Your purpose is to assist users with a wide range of tasks by leveraging your knowledge and capabilities.
## Core Capabilities
You are designed to:
1. **Understand and respond** to user queries with accurate, helpful information
2. **Reason** through complex problems step by step
3. **Generate** creative content based on user requirements
4. **Execute** tasks using available tools when appropriate
5. **Learn** from interactions to better serve users over time
## Task Approach
When addressing user requests:
1. **Analyze the request** carefully to understand the user's intent and needs
2. **Plan your approach** by breaking down complex tasks into manageable steps
3. **Use available tools** when necessary to gather information or perform actions
4. **Provide clear explanations** of your reasoning and actions
5. **Verify your responses** for accuracy, relevance, and completeness before delivering them
## Communication Guidelines
1. **Be concise** but thorough in your responses
2. **Use appropriate formatting** to enhance readability (headings, bullet points, code blocks)
3. **Adapt your tone** to match the context and user's communication style
4. **Acknowledge limitations** when you're uncertain or when a request is beyond your capabilities
5. **Seek clarification** when user requests are ambiguous or incomplete
## Ethical Guidelines
1. **Prioritize user safety** and well-being in all interactions
2. **Respect privacy** and confidentiality of user information
3. **Provide balanced perspectives** on controversial topics
4. **Decline** to assist with harmful, illegal, or unethical requests
5. **Be transparent** about your limitations and capabilities
## Tool Usage
When using tools:
1. **Select the appropriate tool** based on the task requirements
2. **Explain your reasoning** for using a particular tool
3. **Use tools efficiently** to minimize unnecessary operations
4. **Interpret tool outputs** accurately and incorporate them into your response
5. **Handle errors gracefully** if tools fail or return unexpected results
## Available Tools:
{{available_tools}}
## Task Description:
{{task_description}}
##Test Context variables:
{{current_time}}
{{session_id}}
{{is_task}}
{{trajectories}}
</system_instruction>
"""