repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/vector/dbs/chroma.py
.py
""" ChromaDB vector database implementation for aworld. This implementation is based on the open-webui project's ChromaDB vector database code. Special thanks to the open-webui contributors for their excellent work. Reference: https://github.com/open-webui/open-webui/blob/main/backend/open_webui/retrieval/vector/dbs/...
344
13,379
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/vector/dbs/base.py
.py
from abc import ABC, abstractmethod from typing import Optional, List from aworld.memory.embeddings.base import EmbeddingsResults, EmbeddingsResult class VectorDB(ABC): """Abstract base class for vector databases. This class defines the standard interface that all vector database implementations mus...
123
3,953
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/longterm/default.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import asyncio import json import traceback from datetime import datetime from typing import Any, List, Literal, Optional, Tuple from aworld.core.memory import MemoryItem, LongTermConfig, MemoryStore, MemoryBase from aworld.models.llm import LLMModel, acall_llm_model f...
362
15,971
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/longterm/__init__.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from .base import MemoryOrchestrator, MemoryGungnir, MemoryProcessingTask, MemoryProcessingResult from aworld.core.memory import LongTermConfig, TriggerConfig, ExtractionConfig, StorageConfig, ProcessingConfig from .default import DefaultMemoryOrchestrator __all__ = [...
19
573
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/longterm/base.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import uuid from abc import ABC, abstractmethod from datetime import datetime from typing import List, Any, Optional, Literal from pydantic import BaseModel, Field from aworld.core.memory import MemoryStore, LongTermConfig from aworld.models.llm import LLMModel from ...
159
5,791
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/db/__init__.py
.py
""" Database implementations for memory storage. """ from .postgres import PostgresMemoryStore from .sqlite import SQLiteMemoryStore __all__ = [ "PostgresMemoryStore", "SQLiteMemoryStore" ]
12
200
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/db/postgres.py
.py
from datetime import datetime from typing import Optional from typing import Optional import pytz # Add pytz for timezone handling from pydantic import BaseModel from aworld.core.memory import MemoryStore from aworld.memory.models import ( MemoryItem, MemoryAIMessage, MemoryHumanMessage, MemorySummary, MemorySys...
363
14,314
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/memory/db/sqlite.py
.py
import json import sqlite3 from datetime import datetime from typing import Optional, List, Dict, Any from pathlib import Path from pydantic import BaseModel from aworld.core.memory import MemoryStore from aworld.memory.models import ( MemoryItem, MemoryAIMessage, MemoryHumanMessage, MemorySummary, MemorySyst...
423
17,935
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/anthropic_provider.py
.py
import os from typing import Any, Dict, List, Generator, AsyncGenerator from aworld.utils import import_package from aworld.logs.util import logger from aworld.core.llm_provider import LLMProviderBase from aworld.models.model_response import ModelResponse, LLMResponseError class AnthropicProvider(LLMProviderBase): ...
334
13,092
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/openai_tokenizer.py
.py
# Copyright 2024 AWorld Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
238
8,634
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/utils.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import copy import inspect import os.path from typing import Dict, Any, List, Union from aworld.core.context.base import Context from aworld.logs.util import logger from aworld.models.qwen_tokenizer import qwen_tokenizer from aworld.models.openai_tokenizer import opena...
208
8,083
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/llm_http_handler.py
.py
"""HTTP handler for LLM providers. This module provides a generic HTTP handler for making requests to LLM providers when direct SDK usage is not desired. """ import json import asyncio import random import time from typing import Any, Dict, List, Optional, Union, Generator, AsyncGenerator import requests from request...
398
13,855
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/llm.py
.py
import traceback from typing import ( List, Dict, Union, Generator, AsyncGenerator, ) from aworld.config import ConfigDict, ModelConfig from aworld.config.conf import AgentConfig, ClientType from aworld.logs.util import logger from aworld.core.llm_provider import LLMProviderBase from aworld.models....
609
22,201
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/openai_provider.py
.py
import os import traceback from typing import Any, Dict, List, Generator, AsyncGenerator from openai import OpenAI, AsyncOpenAI from aworld.config.conf import ClientType from aworld.core.llm_provider import LLMProviderBase from aworld.models.llm_http_handler import LLMHTTPHandler from aworld.models.model_response imp...
637
26,610
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/model_response.py
.py
from typing import Any, Dict, List, Optional import json from pydantic import BaseModel from aworld.logs.util import logger class LLMResponseError(Exception): """Represents an error in LLM response. Attributes: message: Error message model: Model name response: Original response ...
656
24,382
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/qwen_tokenizer.py
.py
# Copyright 2023 The Qwen team, Alibaba Group. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
246
9,022
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/models/ant_provider.py
.py
import ast import asyncio import datetime import html import json import os import time from typing import ( Any, List, Dict, Generator, AsyncGenerator, ) from binascii import b2a_hex from aworld.config.conf import ClientType from aworld.core.llm_provider import LLMProviderBase from aworld.models....
867
35,130
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/agents/llm_agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import copy import json import time import traceback import uuid from collections import OrderedDict from datetime import datetime from typing import Dict, Any, List, Callable, Optional import aworld.trace as trace from aworld.core.agent.agent_desc import get_agent_des...
936
44,852
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/agents/parallel_llm_agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import asyncio from typing import List, Dict, Any, Callable from aworld.agents.llm_agent import Agent from aworld.core.common import Observation, ActionModel from aworld.core.event.base import Message from aworld.utils.run_util import exec_agent class ParallelizableA...
68
2,814
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/agents/task_llm_agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from typing import List, Dict, Any from aworld.core.exceptions import AWorldRuntimeException from aworld.core.agent.swarm import Swarm from aworld.core.task import Task, TaskResponse from aworld.utils.run_util import exec_tasks from aworld.agents.llm_agent import Age...
48
1,566
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/agents/loop_llm_agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from typing import Any, Callable from aworld.agents.llm_agent import Agent class LoopableAgent(Agent): """Support for loop agents in the swarm. The parameters of the extension function are the agent itself, which can obtain internal information of the agent....
47
1,481
ai-agent-book
chapter9/gaia-experience/AWorld/aworld/agents/serial_llm_agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from typing import List, Dict, Any, Callable from aworld.core.event.base import Message from aworld.utils.run_util import exec_agent from aworld.agents.llm_agent import Agent from aworld.core.common import Observation, ActionModel, Config from aworld.logs.util import...
65
2,573
ai-agent-book
chapter9/gaia-experience/AWorld/examples/phone_use/utils.py
.py
# coding: utf-8 import json import traceback import uuid from dataclasses import dataclass, field from pathlib import Path from typing import Any, Optional, Dict, List from langchain_core.load import dumpd, load from langchain_core.messages import BaseMessage, AIMessage, ToolMessage, SystemMessage, HumanMessage from ...
278
9,341
ai-agent-book
chapter9/gaia-experience/AWorld/examples/phone_use/run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.config import AgentConfig from aworld.core.task import Task from aworld.runner import Runners from examples.common.tools.common import Agents, Tools from examples.common.tools.conf import AndroidToolConfig from examples.phone_use.agent import Andr...
40
1,279
ai-agent-book
chapter9/gaia-experience/AWorld/examples/phone_use/prompts.py
.py
SYSTEM_PROMPT = """ You are an Android device automation assistant. Your task is to help users perform various operations on Android devices. You can perform the following actions: 1.Tap Element (tap) - Requires parameter: index (element number) 2.Input Text (input_text) - Requires parameter: text (text content to inpu...
58
2,850
ai-agent-book
chapter9/gaia-experience/AWorld/examples/phone_use/agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import json import time import traceback from typing import Dict, Any, Optional, List, Union from langchain_core.messages import HumanMessage, BaseMessage, SystemMessage from examples.phone_use.prompts import SYSTEM_PROMPT, LAST_STEP_PROMPT from examples.phone_use.ut...
253
9,267
ai-agent-book
chapter9/gaia-experience/AWorld/examples/parallel_run/run.py
.py
import os from aworld.agents.llm_agent import Agent from aworld.config.conf import AgentConfig from aworld.core.task import Task from aworld.runner import Runners from aworld.config import RunConfig, EngineName # Setup, need modify os.environ["LLM_PROVIDER"] = "openai" os.environ["LLM_MODEL_NAME"] = "gpt-4o" os.enviro...
42
1,329
ai-agent-book
chapter9/gaia-experience/AWorld/examples/HITP/run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.agents.llm_agent import Agent from aworld.config.conf import AgentConfig from aworld.core.agent.swarm import Swarm from aworld.logs.util import color_log, Color from aworld.runner import Runners from aworld.tools.human.human import HUMAN import ex...
35
1,064
ai-agent-book
chapter9/gaia-experience/AWorld/examples/imo/utils.py
.py
import json import logging import os import re import string from pathlib import Path from typing import Any, Dict, List, Optional from tabulate import tabulate logger = logging.getLogger(__name__) def normalize_str(input_str, remove_punct=True) -> str: no_spaces = re.sub(r"\s", "", input_str) if remove_pun...
273
9,333
ai-agent-book
chapter9/gaia-experience/AWorld/examples/imo/run.py
.py
import argparse import json import logging import os import re import sys import traceback from pathlib import Path from typing import Any, Dict, List from dotenv import load_dotenv from pathlib import Path from aworld.agents.llm_agent import Agent from aworld.config.conf import AgentConfig, TaskConfig from aworld.co...
307
11,553
ai-agent-book
chapter9/gaia-experience/AWorld/examples/imo/prompt.py
.py
# MIT License # # Copyright (c) 2025 Lin Yang, Yichen Huang # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modi...
63
4,148
ai-agent-book
chapter9/gaia-experience/AWorld/examples/imo/guard_tool_caller.py
.py
# MIT License # # Copyright (c) 2025 Lin Yang, Yichen Huang # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modi...
165
9,089
ai-agent-book
chapter9/gaia-experience/AWorld/examples/osworld/run_multienv_aworldAgent.py
.py
from __future__ import annotations import argparse import datetime import json import logging import os import sys import signal import time from typing import List, Dict, Any, Optional import math from tqdm import tqdm from multiprocessing import Process, Manager from multiprocessing import current_process import lib_...
741
28,556
ai-agent-book
chapter9/gaia-experience/AWorld/examples/osworld/aworldAgent/workflow.py
.py
""" This code is adapted from AgentS2 (https://github.com/simular-ai/Agent-S) with modifications to suit specific requirements. """ import logging import textwrap from typing import Dict, List, Tuple from aworld.config.conf import AgentConfig from aworld.agents.llm_agent import Agent from aworld.core.common import Obs...
230
8,535
ai-agent-book
chapter9/gaia-experience/AWorld/examples/osworld/aworldAgent/utils.py
.py
""" This code is adapted from AgentS2 (https://github.com/simular-ai/Agent-S) with modifications to suit specific requirements. """ import re import base64 from aworld.core.common import Observation, ActionModel from aworld.models.model_response import ModelResponse from aworld.core.agent.base import AgentResult from a...
194
7,578
ai-agent-book
chapter9/gaia-experience/AWorld/examples/osworld/aworldAgent/grounding.py
.py
""" This code is adapted from AgentS2 (https://github.com/simular-ai/Agent-S) with modifications to suit specific requirements. """ import ast import re import textwrap from collections import defaultdict from io import BytesIO from typing import Any, Dict, List, Optional, Tuple, Union import pytesseract from PIL impo...
5,253
211,860
ai-agent-book
chapter9/gaia-experience/AWorld/examples/osworld/aworldAgent/prompt.py
.py
""" This code is adapted from AgentS2 (https://github.com/simular-ai/Agent-S) with modifications to suit specific requirements. """ GENERATOR_SYS_PROMPT = """You are an expert in graphical user interfaces and Python code. You are responsible for executing the task: `TASK_DESCRIPTION`. You are working in Ubuntu. You are...
948
41,479
ai-agent-book
chapter9/gaia-experience/AWorld/examples/osworld/aworldAgent/agent.py
.py
""" This code is adapted from AgentS2 (https://github.com/simular-ai/Agent-S) with modifications to suit specific requirements. """ import logging import platform from typing import Dict, List, Tuple from aworldAgent.grounding import ACI from aworldAgent.workflow import Worker logger = logging.getLogger("desktopenv.a...
100
3,178
ai-agent-book
chapter9/gaia-experience/AWorld/examples/BFCL/run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.config.conf import AgentConfig from aworld.agents.llm_agent import Agent from aworld.runner import Runners import json if __name__ == "__main__": agent_config = AgentConfig( llm_provider=os.getenv("LLM_PROVIDER", "openai"), l...
55
1,767
ai-agent-book
chapter9/gaia-experience/AWorld/examples/BFCL/mcp_tools/tool_base.py
.py
import logging from pathlib import Path from typing import Any, Literal from mcp.server import FastMCP from pydantic import BaseModel, Field from aworld.logs.util import Color from examples.gaia.utils import color_log, setup_logger class ActionArguments(BaseModel): r"""Protocol: MCP Action Arguments""" nam...
52
1,910
ai-agent-book
chapter9/gaia-experience/AWorld/examples/BFCL/mcp_tools/test_server.py
.py
#!/usr/bin/env python3 """ Test script for GorillaFileSystem MCP Functions This script tests all mcp_ functions in the GorillaFileSystem class. Run this to verify all file system operations work correctly. """ import sys import os import traceback # Add the current directory to the path to import gorilla_file_system...
318
10,288
ai-agent-book
chapter9/gaia-experience/AWorld/examples/BFCL/mcp_tools/__init__.py
.py
""" MCP Tools Package This package contains MCP (Model Context Protocol) tools and servers for various functionalities including file system operations. """ from .gorilla_file_system import GorillaFileSystem __all__ = [ "GorillaFileSystem" ] __version__ = "1.0.0"
15
272
ai-agent-book
chapter9/gaia-experience/AWorld/examples/BFCL/mcp_tools/long_context.py
.py
WATCH_LIST_EXTENSION = ['JHGUN', 'LMAT', 'YNK', 'W', 'XSW', 'XZEHV', 'R', 'UIENW', 'H', 'P', 'JN', 'OQAI', 'FBIS', 'DZ', 'K', 'JNZD', 'IJXX', 'Z', 'J', 'FJD', 'D', 'NMONY', 'GMRH', 'LS', 'G', 'VEUCA', 'KBWCK', 'BAJ', 'V', 'FTCW', 'YOTF', 'PU', 'GOUW', 'UMQJN', 'KSA', 'HDYC', 'HTTKI',...
408
190,330
ai-agent-book
chapter9/gaia-experience/AWorld/examples/BFCL/mcp_tools/gorilla_file_system.py
.py
import datetime from copy import deepcopy from typing import Dict, List, Optional, Union from pydantic import Field from aworld.logs.util import Color import traceback from examples.BFCL.mcp_tools.tool_base import ActionArguments, ActionCollection FILE_CONTENT_EXTENSION = "The company's financials for the year reflec...
952
50,808
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/run.py
.py
import asyncio import os import uuid from dotenv import load_dotenv from aworld import trace from examples.multi_agents.collaborative.debate.agent.debate_agent import DebateAgent from examples.multi_agents.collaborative.debate.agent.main import DebateArena from examples.multi_agents.collaborative.debate.agent.moderat...
60
2,247
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/stream_output_agent.py
.py
from aworld.config import AgentConfig from aworld.agents.llm_agent import Agent from aworld.models.llm import acall_llm_model_stream from aworld.output import MessageOutput class StreamOutputAgent(Agent): def __init__(self, conf: AgentConfig, name: str, **kwargs): super().__init__(conf, name) async d...
19
715
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/main.py
.py
import logging from typing import Optional, AsyncGenerator from aworld.memory.main import MemoryFactory from examples.multi_agents.collaborative.debate.agent.base import DebateSpeech from examples.multi_agents.collaborative.debate.agent.debate_agent import DebateAgent from examples.multi_agents.collaborative.debate.ag...
210
7,729
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/debate_agent.py
.py
import logging from abc import ABC from typing import Dict, Any, Union, List, Literal, Optional from datetime import datetime import uuid from aworld.models.model_response import ToolCall from examples.multi_agents.collaborative.debate.agent.base import DebateSpeech from examples.multi_agents.collaborative.debate.agen...
220
9,570
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/moderator_agent.py
.py
import logging from abc import ABC from datetime import datetime from typing import Dict, Any, Union, List from pydantic import Field from aworld.core.common import Observation, ActionModel from aworld.output import MessageOutput, WorkSpace, ArtifactType, SearchOutput from examples.multi_agents.collaborative.debate.a...
140
5,372
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/prompts.py
.py
user_assignment_system_prompt = "You are a helpful search agent." user_assignment_prompt = """ While facing the hot topic: {topic}, your opinion is {opinion}. You stand on your opinion and fight any other opinion (such as {oppose_opinion}) that differs from your opinion. You have an assistant that can help search the...
252
14,279
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/base.py
.py
from pydantic import BaseModel, Field from aworld.output import Output import asyncio from aworld.output.base import OutputPart class DebateSpeech(Output, BaseModel): name: str = Field(default="", description="name of the speaker") type: str = Field(default="", description="speech type") stance: str = F...
46
1,645
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/search/search_engine.py
.py
import asyncio from enum import Enum from typing import List class SearchAPI(Enum): PERPLEXITY = "perplexity" TAVILY = "tavily" EXA = "exa" ARXIV = "arxiv" PUBMED = "pubmed" LINKUP = "linkup" class SearchException(Exception): def __init__(self, message, error_code=None): super()...
49
1,409
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/debate/agent/search/tavily_search_engine.py
.py
from examples.multi_agents.collaborative.debate.agent.search.search_engine import SearchEngine class TavilySearchEngine(SearchEngine): """Tavily""" async def async_search(self, query: str, max_results=5, include_raw_content=False, **kwargs) -> dict: """ Performs concurrent web searches us...
47
1,951
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/travel/run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.config.conf import AgentConfig, ToolConfig from aworld.agents.llm_agent import Agent from aworld.config import ModelConfig from aworld.core.agent.swarm import TeamSwarm, Swarm, GraphBuildType from aworld.core.task import Task from aworld.runner imp...
96
3,793
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/collaborative/travel/prompts.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. plan_sys_prompt = """ You are an AI agent designed to automate tasks. Your goal is to accomplish the ultimate task following the rules. # Input Format Task Previous steps # Response Rules 1. RESPONSE FORMAT: You must ALWAYS respond with valid JSON or text. 2. ACTION...
75
4,422
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/run.py
.py
import os from aworld.agents.llm_agent import Agent from aworld.config.conf import AgentConfig, ModelConfig from aworld.core.agent.swarm import TeamSwarm from aworld.core.event.base import Constants from aworld.runner import Runners from examples.common.tools.common import Tools from examples.multi_agents.coordinatio...
72
2,206
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/prompts.py
.py
parallel_plan_sys_prompt = """## Task You are an information search expert. Your goal is to maximize the retrieval of effective information through search task planning and retrieval. Please plan the necessary search and processing steps to solve the problem based on the user's question and background information. ##...
311
13,630
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/planner/parse.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import json import traceback from aworld.logs.util import logger from examples.multi_agents.coordination.deepresearch.planner.models import Plan, StepInfos def parse_step_infos(step_infos: dict) -> StepInfos: """Parse step information dictionary into StepInfos ob...
32
967
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/planner/models.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import json import traceback from typing import Optional, Dict, Any, Union, List from pydantic import BaseModel, Field from aworld.logs.util import logger class StepInfo(BaseModel): """Step information details""" # input for agent input: Optional[str] =...
58
1,713
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/planner/__init__.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. """AWorld planner module for agent planning and reasoning capabilities. This module provides planning capabilities inspired by langchain-experimental planners, adapted for AWorld's Context and ModelResponse systems with StringPromptTemplate support. """ from .models im...
27
883
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/planner/plan_handler.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import asyncio import uuid from typing import AsyncGenerator from aworld.core.common import ActionModel, Observation, TaskItem from aworld.core.event.base import AgentMessage, Constants, TopicType, Message from aworld.core.exceptions import AWorldRuntimeException from ...
141
6,978
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/deepresearch/planner/plan.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import json import re from aworld.core.agent.base import AgentResult from aworld.core.common import ActionModel from aworld.core.model_output_parser import ModelOutputParser from aworld.logs.util import logger from aworld.models.model_response import ModelResponse from...
100
3,959
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/master_worker/__init__.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. """ TeamSwarm示例模块 """
5
80
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/master_worker/run.py
.py
import os from pathlib import Path import sys project_root = Path(__file__).parent.parent.parent sys.path.insert(0, str(project_root)) from aworld.core.agent.swarm import TeamSwarm from aworld.runner import Runners from examples.common.tools.common import Tools from aworld.agents.llm_agent import Agent from aworld.c...
95
3,310
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/master_worker/prompts_single_action.py
.py
""" Contains various prompt templates used in the TeamSwarm example (single-action version) """ # System prompt for the planning agent plan_sys_prompt = """## Task You are an information search expert. Your goal is to maximize the acquisition of effective information through search task planning and retrieval. Based o...
77
4,023
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/master_worker/run_multi_action.py
.py
import os from pathlib import Path import sys project_root = Path(__file__).parent.parent.parent sys.path.insert(0, str(project_root)) from aworld.core.agent.swarm import TeamSwarm from aworld.runner import Runners from examples.common.tools.common import Tools from aworld.agents.llm_agent import Agent from aworld.c...
95
3,287
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/master_worker/prompts_multi_actions.py
.py
""" Contains various prompt templates used in the TeamSwarm example """ # System prompt for the planning agent plan_sys_prompt = """## Task You are an information search expert. Your goal is to maximize the acquisition of effective information through search task planning and retrieval. Please plan the search and proc...
83
4,217
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/custom_agent/utils.py
.py
import re from typing import Any, Dict, List, Literal, Optional, Union, Tuple import logging as logger def extract_pattern(content: str, pattern: str) -> Optional[str]: try: _pattern = fr"<{pattern}>(.*?)</{pattern}>" match = re.search(_pattern, content, re.DOTALL) if match: te...
18
548
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/custom_agent/run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.config.conf import ModelConfig, AgentConfig from aworld.core.agent.swarm import Swarm, GraphBuildType from aworld.core.task import Task from aworld.runner import Runners from examples.multi_agents.coordination.custom_agent.agent import PlanAgent, ...
57
1,935
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/custom_agent/mock.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.utils.import_package import import_packages import_packages(["pandas", "numpy"]) import pandas as pd import numpy as np from aworld.utils import import_package def mock_dataset(name: str): if name == 'gaia': npy_path = f"{os.getcw...
28
694
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/custom_agent/prompts.py
.py
init_prompt = f""" Please give me clear step-by-step instructions to complete the entire task. If the task needs any special knowledge, let me know which tools I should use to help me get it done. """ execute_system_prompt = """ ===== RULES FOR THE ASSISTANT ===== You are my assistant, and I am your user. Always remem...
89
6,215
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/coordination/custom_agent/agent.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import copy import json import traceback from typing import Dict, Any, List, Union from aworld.core.event.base import Message from aworld.utils.common import sync_exec from examples.multi_agents.coordination.custom_agent.prompts import execute_system_prompt, plan_syste...
252
10,659
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/workflow/search/hybrid_swarm_run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from aworld.core.agent.swarm import Swarm from aworld.runner import Runners from examples.multi_agents.workflow.search.common import * if __name__ == "__main__": s1 = Swarm(search) s2 = Swarm(summary) # default is workflow swarm # swarm1 and swarm2 are ...
22
653
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/workflow/search/run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from aworld.core.agent.swarm import Swarm from aworld.runner import Runners from examples.multi_agents.workflow.search.common import * # os.environ["LLM_MODEL_NAME"] = "YOUR_LLM_MODEL_NAME" # os.environ["LLM_BASE_URL"] = "YOUR_LLM_BASE_URL" # os.environ["LLM_API_KEY"] ...
28
925
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/workflow/search/parallel_run.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from aworld.core.agent.swarm import Swarm from aworld.runner import Runners from examples.multi_agents.workflow.search.common import * if __name__ == "__main__": search2 = Agent( conf=agent_config, name="search_agent", system_prompt=search_s...
29
880
ai-agent-book
chapter9/gaia-experience/AWorld/examples/multi_agents/workflow/search/common.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. import os from aworld.agents.llm_agent import Agent from aworld.config.conf import AgentConfig from examples.common.tools.common import Tools search_sys_prompt = "You are a helpful search agent." search_prompt = """ Please act as a search agent, constructing appro...
50
1,472
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/gaia_agent_server.py
.py
from typing import AsyncGenerator import traceback import logging import os import json import sys import uuid import time logger = logging.getLogger(__name__) class GaiaAgentServer: def __init__(self): pass def _get_model_config(self): try: llm_provider = os.getenv("LLM_PROVIDER...
137
4,315
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/utils.py
.py
import json import logging import os import re import string from pathlib import Path from typing import Any, Dict, List, Optional from tabulate import tabulate from aworld.logs.util import Color logger = logging.getLogger(__name__) def normalize_str(input_str, remove_punct=True) -> str: no_spaces = re.sub(r"\...
251
8,437
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/__init__.py
.py
# coding: utf-8 # Copyright (c) 2025 inclusionAI. from aworld.utils import import_packages import_packages(["dotenv"]) from dotenv import load_dotenv load_dotenv()
8
165
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/run.py
.py
import argparse import json import logging import os import re import traceback from pathlib import Path from typing import Any, Dict, List from dotenv import load_dotenv from aworld.agents.llm_agent import Agent from aworld.config.conf import AgentConfig, TaskConfig from aworld.core.task import Task from aworld.runn...
229
8,218
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/gaia_agent_runner.py
.py
import json import logging import os import re import subprocess import sys import traceback from typing import AsyncGenerator import uuid from aworld.cmd.utils.agent_ui_parser import ( AWorldWebAgentUI, BaseToolResultParser, ToolCard, ToolResultParserFactory, ) from aworld.config.conf import AgentConfi...
347
11,933
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/prompt.py
.py
system_prompt = """You are an all-capable AI assistant, aimed at solving any task presented by the user. ## Task Description: Please note that the task can be very complex. Do not attempt to solve it all at once. You should break the task down and use different tools step by step to solve it. After using each tool, cl...
38
2,925
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/prompt_w_guard.py
.py
system_prompt = """You are an all-capable AI assistant, aimed at solving any task presented by the user. ## Task Description: Please note that the task can be very complex. Do not attempt to solve it all at once. You should break the task down and use different tools step by step to solve it. After using each tool, cl...
46
4,223
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/cmd/agent_deploy/gaia_agent/agent.py
.py
import logging import os from aworld.cmd.data_model import BaseAWorldAgent, ChatCompletionRequest from examples.gaia.gaia_agent_runner import GaiaAgentRunner logger = logging.getLogger(__name__) class AWorldAgent(BaseAWorldAgent): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) ...
43
1,559
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/utils.py
.py
import os import tempfile import traceback from pathlib import Path from urllib.parse import urlparse import magic import requests def is_url(path_or_url: str) -> bool: """ Check if the given string is a URL. Args: path_or_url: String to check Returns: bool: True if the string is a ...
170
5,669
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/base.py
.py
import logging import os from pathlib import Path from typing import Any, Literal from mcp.server import FastMCP from pydantic import BaseModel, Field from aworld.logs.util import Color from examples.gaia.utils import color_log, setup_logger class ActionArguments(BaseModel): r"""Protocol: MCP Action Arguments""...
103
3,703
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/media/image.py
.py
import base64 import os import time import traceback from io import BytesIO from pathlib import Path from typing import Any import pytesseract from dotenv import load_dotenv from PIL import Image, ImageEnhance, ImageFilter from pydantic import BaseModel, Field from pydantic.fields import FieldInfo from aworld.config....
485
18,625
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/media/video.py
.py
""" Video MCP Service This module provides MCP service functionality for video operations including: - Video content analysis with AI-powered insights - Video summarization and key point extraction - Keyframe extraction with scene detection - Subtitle extraction from video content It handles various video formats wit...
993
35,987
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/media/audio.py
.py
import json import os import subprocess import time import traceback from pathlib import Path from typing import Any, Literal from dotenv import load_dotenv from openai import OpenAI from pydantic import BaseModel, Field from pydantic.fields import FieldInfo from aworld.logs.util import Color from examples.gaia.mcp_c...
556
23,037
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/wiki.py
.py
""" Wikipedia MCP Server This module provides MCP server functionality for interacting with Wikipedia. It supports searching Wikipedia, retrieving article content, and getting summaries. Key features: - Search Wikipedia for articles - Retrieve full article content - Get article summaries - Fetch random articles - Get...
1,058
41,431
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/yahoofinance.py
.py
""" Yahoo Finance MCP Action Collection This module provides Yahoo Finance data access through the ActionCollection framework. It supports stock quotes, historical data, company information, financial statements, news search, and market summaries with LLM-optimized output formatting. Key features: - Real-time stock q...
622
25,738
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/pubchem.py
.py
""" PubChem MCP Server This module provides MCP server functionality for accessing PubChem database programmatically. It supports compound searches, property retrieval, and structure-based queries using PubChem's REST API. Key features: - Compound search by name, CID, SMILES, or InChI - Property retrieval (molecular ...
642
26,335
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/download.py
.py
""" Download MCP Server This module provides MCP server functionality for downloading files from URLs. It supports HTTP/HTTPS downloads with configurable options and returns LLM-friendly formatted results. Key features: - Download files from HTTP/HTTPS URLs - Configurable timeout and overwrite options - Custom header...
480
17,098
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/youtube.py
.py
""" YouTube MCP Service This module provides MCP service functionality for YouTube operations including: - Downloading videos from YouTube URLs - Extracting transcripts from YouTube videos It handles various scenarios with proper validation, error handling, and progress tracking while providing LLM-friendly formatted...
550
20,789
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/wayback.py
.py
""" Wayback Machine MCP Server This module provides MCP server functionality for interacting with the Wayback Machine. It supports listing archived versions, fetching archived content, and saving pages to the archive. Key features: - List available archived versions of URLs with date filtering - Fetch content from sp...
542
21,721
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/terminal.py
.py
""" Terminal MCP Server This module provides MCP server functionality for executing terminal commands safely. It supports command execution with timeout controls and returns LLM-friendly formatted results. Key features: - Execute terminal commands with configurable timeouts - Cross-platform command execution support ...
513
19,008
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/search.py
.py
""" Search MCP Server This module provides MCP server functionality for performing web searches using various search engines. It supports structured queries and returns LLM-friendly formatted search results. Key features: - Perform web searches using Google Custom Search API - Filter and format search results for LLM...
388
14,676
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/playchess.py
.py
""" Chess MCP Server This module provides MCP server functionality for chess game operations and analysis. It utilizes the 'python-chess' library to support various chess-related tasks. Key features: - Manage chess game states (new game, load FEN, make moves) - Validate and execute moves in UCI or SAN format - Get le...
536
22,803
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/browser.py
.py
""" Browser MCP Server This module provides MCP server functionality for browser automation and interaction. It handles tasks such as web scraping, form submission, and automated browsing using browser-use package. Main functions: - mcp_browser_use: Performs browser automation tasks with LLM-friendly output """ impo...
375
14,184
ai-agent-book
chapter9/gaia-experience/AWorld/examples/gaia/mcp_collections/tools/mcparxiv.py
.py
""" ArXiv MCP Server This module provides MCP server functionality for ArXiv academic paper operations. It supports paper search, metadata extraction, and content retrieval with LLM-friendly formatting. Key features: - Search ArXiv papers by query, author, category, or ID - Extract paper metadata (title, authors, abs...
724
28,179