fix(docs): update doc example code to work (#2624)

Co-authored-by: alan.cl <alan.cl@antgroup.com>
This commit is contained in:
alanchen
2025-04-15 22:45:55 +08:00
committed by GitHub
parent 5e7f3568d3
commit 7de6937865
6 changed files with 57 additions and 26 deletions

View File

@@ -26,7 +26,7 @@ context: AgentContext = AgentContext(
) )
# Create an agent memory, default memory is ShortTermMemory # Create an agent memory, default memory is ShortTermMemory
agent_memory: AgentMemory = AgentMemory() agent_memory: AgentMemory = AgentMemory()
agent_memory.gpts_memory.init(conv_id="test123")
system_prompt_template = """\ system_prompt_template = """\
You are a {{ role }}, {% if name %}named {{ name }}, {% endif %}your goal is {{ goal }}. You are a {{ role }}, {% if name %}named {{ name }}, {% endif %}your goal is {{ goal }}.

View File

@@ -10,7 +10,7 @@ summarizer.
Install the required packages by running the following command: Install the required packages by running the following command:
```bash ```bash
pip install "dbgpt[agent]>=0.5.6rc1" -U pip install "dbgpt[agent,simple_framework]>=0.7.0" "dbgpt_ext>=0.7.0" -U
pip install openai pip install openai
``` ```
@@ -286,8 +286,8 @@ class SummaryActionInput(BaseModel):
) )
class SummaryAction(Action[SummaryActionInput]): class SummaryAction(Action[SummaryActionInput]):
def __init__(self): def __init__(self, **kwargs):
super().__init__() super().__init__(**kwargs)
@property @property
def resource_need(self) -> Optional[ResourceType]: def resource_need(self) -> Optional[ResourceType]:
@@ -371,9 +371,9 @@ class MySummarizerAgent(ConversableAgent):
### Action Extended Parameter Processing ### Action Extended Parameter Processing
```python ```python
from typing import Optional, Dict, Any from typing import Optional, Dict, Any, List
from pydantic import BaseModel from pydantic import BaseModel
from dbgpt.agent import Action, ActionOutput, AgentResource, ConversableAgent from dbgpt.agent import Agent, Action, AgentMessage, ActionOutput, AgentResource, ConversableAgent
class SummaryActionInput(BaseModel): class SummaryActionInput(BaseModel):
@@ -399,7 +399,13 @@ class MySummarizerAgent(ConversableAgent):
super().__init__(**kwargs) super().__init__(**kwargs)
self._init_actions([SummaryAction]) self._init_actions([SummaryAction])
def prepare_act_param(self) -> Dict[str, Any]: def prepare_act_param(
self,
received_message: Optional[AgentMessage],
sender: Agent,
rely_messages: Optional[List[AgentMessage]] = None,
**kwargs,
) -> Dict[str, Any]:
return {"action_extra_param_key": "this is extra param"} return {"action_extra_param_key": "this is extra param"}
``` ```
@@ -410,6 +416,7 @@ After the custom agent is created, you can use it in the following way:
```python ```python
import asyncio import asyncio
import os
from dbgpt.agent import AgentContext, ConversableAgent, AgentMemory, LLMConfig, UserProxyAgent from dbgpt.agent import AgentContext, ConversableAgent, AgentMemory, LLMConfig, UserProxyAgent
from dbgpt.model.proxy import OpenAILLMClient from dbgpt.model.proxy import OpenAILLMClient
@@ -418,10 +425,15 @@ class MySummarizerAgent(ConversableAgent):
... ...
async def main(): async def main():
llm_client = OpenAILLMClient(model_alias="gpt-3.5-turbo") llm_client = OpenAILLMClient(
model_alias="gpt-3.5-turbo", # or other models, eg. "gpt-4o"
api_base=os.getenv("OPENAI_API_BASE"),
api_key=os.getenv("OPENAI_API_KEY"),
)
context: AgentContext = AgentContext(conv_id="summarize") context: AgentContext = AgentContext(conv_id="summarize")
agent_memory: AgentMemory = AgentMemory() agent_memory: AgentMemory = AgentMemory()
agent_memory.gpts_memory.init(conv_id="summarize")
summarizer = ( summarizer = (
await MySummarizerAgent() await MySummarizerAgent()
@@ -457,7 +469,7 @@ async def main():
Nuclear electric rocket Nuclear electric rocket
""", """,
) )
print(await agent_memory.gpts_memory.one_chat_completions("summarize")) print(await agent_memory.gpts_memory.app_link_chat_message("summarize"))
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())
@@ -467,9 +479,11 @@ Full code as follows:
```python ```python
import asyncio import asyncio
from typing import Any, Dict, Optional, Tuple import os
from typing import Any, Dict, Optional, Tuple, List
from dbgpt.agent import ( from dbgpt.agent import (
Agent,
Action, Action,
ActionOutput, ActionOutput,
AgentContext, AgentContext,
@@ -548,7 +562,13 @@ class MySummarizerAgent(ConversableAgent):
reply_message.context = {"not_related_message": NOT_RELATED_MESSAGE} reply_message.context = {"not_related_message": NOT_RELATED_MESSAGE}
return reply_message return reply_message
def prepare_act_param(self) -> Dict[str, Any]: def prepare_act_param(
self,
received_message: Optional[AgentMessage],
sender: Agent,
rely_messages: Optional[List[AgentMessage]] = None,
**kwargs,
) -> Dict[str, Any]:
return {"action_extra_param_key": "this is extra param"} return {"action_extra_param_key": "this is extra param"}
async def correctness_check( async def correctness_check(
@@ -558,7 +578,7 @@ class MySummarizerAgent(ConversableAgent):
action_report = message.action_report action_report = message.action_report
task_result = "" task_result = ""
if action_report: if action_report:
task_result = action_report.get("content", "") task_result = action_report.content
check_result, model = await self.thinking( check_result, model = await self.thinking(
messages=[ messages=[
@@ -606,8 +626,8 @@ class SummaryActionInput(BaseModel):
class SummaryAction(Action[SummaryActionInput]): class SummaryAction(Action[SummaryActionInput]):
def __init__(self): def __init__(self, **kwargs):
super().__init__() super().__init__(**kwargs)
@property @property
def resource_need(self) -> Optional[ResourceType]: def resource_need(self) -> Optional[ResourceType]:
@@ -671,10 +691,15 @@ class SummaryAction(Action[SummaryActionInput]):
async def main(): async def main():
llm_client = OpenAILLMClient(model_alias="gpt-3.5-turbo") llm_client = OpenAILLMClient(
model_alias="gpt-3.5-turbo", # or other models, eg. "gpt-4o"
api_base=os.getenv("OPENAI_API_BASE"),
api_key=os.getenv("OPENAI_API_KEY"),
)
context: AgentContext = AgentContext(conv_id="summarize") context: AgentContext = AgentContext(conv_id="summarize")
agent_memory: AgentMemory = AgentMemory() agent_memory: AgentMemory = AgentMemory()
agent_memory.gpts_memory.init(conv_id="summarize")
summarizer = ( summarizer = (
await MySummarizerAgent() await MySummarizerAgent()
@@ -709,7 +734,7 @@ async def main():
Nuclear electric rocket Nuclear electric rocket
""", """,
) )
print(await agent_memory.gpts_memory.one_chat_completions("summarize")) print(await agent_memory.gpts_memory.app_link_chat_message("summarize"))
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -9,7 +9,7 @@ the agent to the database.
To use the database in the agent, you need to install the dependencies with the following command: To use the database in the agent, you need to install the dependencies with the following command:
```bash ```bash
pip install "dbgpt[simple_framework]>=0.5.9rc0" pip install "dbgpt[agent,simple_framework]>=0.7.0" "dbgpt_ext>=0.7.0"
``` ```
## Create A Database Connector ## Create A Database Connector
@@ -33,7 +33,7 @@ created in temporary directory and will be deleted after the program exits.
::: :::
```python ```python
from dbgpt.datasource.rdbms.conn_sqlite import SQLiteTempConnector from dbgpt_ext.datasource.rdbms.conn_sqlite import SQLiteTempConnector
connector = SQLiteTempConnector.create_temporary_db() connector = SQLiteTempConnector.create_temporary_db()
connector.create_temp_tables( connector.create_temp_tables(
@@ -65,7 +65,7 @@ We connect to the SQLite database by giving the database file path, please make
::: :::
```python ```python
from dbgpt.datasource.rdbms.conn_sqlite import SQLiteConnector from dbgpt_ext.datasource.rdbms.conn_sqlite import SQLiteConnector
connector = SQLiteConnector.from_file_path("path/to/your/database.db") connector = SQLiteConnector.from_file_path("path/to/your/database.db")
``` ```
@@ -81,7 +81,7 @@ make sure the connection information is correct.
::: :::
```python ```python
from dbgpt.datasource.rdbms.conn_mysql import MySQLConnector from dbgpt_ext.datasource.rdbms.conn_mysql import MySQLConnector
connector = MySQLConnector.from_uri_db( connector = MySQLConnector.from_uri_db(
host="localhost", host="localhost",
@@ -130,6 +130,7 @@ async def main():
conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048 conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048
) )
agent_memory = AgentMemory() agent_memory = AgentMemory()
agent_memory.gpts_memory.init(conv_id="test123")
user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build() user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build()
@@ -149,7 +150,7 @@ async def main():
) )
## dbgpt-vis message infos ## dbgpt-vis message infos
print(await agent_memory.gpts_memory.one_chat_completions("test123")) print(await agent_memory.gpts_memory.app_link_chat_message("test123"))
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -20,7 +20,7 @@ a simple way, only a little change to the code when you need to deploy your agen
Firstly, you need to install the `dbgpt` package with the following command: Firstly, you need to install the `dbgpt` package with the following command:
```bash ```bash
pip install "dbgpt[agent]>=0.5.9rc0" pip install "dbgpt[agent,simple_framework]>=0.7.0" "dbgpt_ext>=0.7.0"
``` ```
Then, you can install the `openai` package with the following command: Then, you can install the `openai` package with the following command:
@@ -81,6 +81,9 @@ async def main():
.bind(agent_memory) .bind(agent_memory)
.build() .build()
) )
# Initialize GptsMemory
agent_memory.gpts_memory.init(conv_id="test123")
# Create a user proxy agent # Create a user proxy agent
user_proxy = await UserProxyAgent().bind(context).bind(agent_memory).build() user_proxy = await UserProxyAgent().bind(context).bind(agent_memory).build()
@@ -92,7 +95,7 @@ async def main():
message="Calculate the result of 321 * 123", message="Calculate the result of 321 * 123",
) )
# Obtain conversation history messages between agents # Obtain conversation history messages between agents
print(await agent_memory.gpts_memory.one_chat_completions("test123")) print(await agent_memory.gpts_memory.app_link_chat_message("test123"))
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -30,7 +30,7 @@ will be created in the temporary directory and will be deleted after the program
Fist, create a temporary SQLite database and create some tables and insert some data: Fist, create a temporary SQLite database and create some tables and insert some data:
```python ```python
from dbgpt.datasource.rdbms.conn_sqlite import SQLiteTempConnector from dbgpt_ext.datasource.rdbms.conn_sqlite import SQLiteTempConnector
connector = SQLiteTempConnector.create_temporary_db() connector = SQLiteTempConnector.create_temporary_db()
connector.create_temp_tables( connector.create_temp_tables(
@@ -140,6 +140,7 @@ async def main():
conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048 conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048
) )
agent_memory = AgentMemory() agent_memory = AgentMemory()
agent_memory.gpts_memory.init(conv_id="test123")
user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build() user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build()
@@ -167,7 +168,7 @@ async def main():
) )
# dbgpt-vis message infos # dbgpt-vis message infos
print(await agent_memory.gpts_memory.one_chat_completions("test123")) print(await agent_memory.gpts_memory.app_link_chat_message("test123"))
if __name__ == "__main__": if __name__ == "__main__":

View File

@@ -82,6 +82,7 @@ async def main():
conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048 conv_id="test123", language="en", temperature=0.5, max_new_tokens=2048
) )
agent_memory = AgentMemory() agent_memory = AgentMemory()
agent_memory.gpts_memory.init(conv_id="test123")
user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build() user_proxy = await UserProxyAgent().bind(agent_memory).bind(context).build()
@@ -107,7 +108,7 @@ async def main():
) )
# dbgpt-vis message infos # dbgpt-vis message infos
print(await agent_memory.gpts_memory.one_chat_completions("test123")) print(await agent_memory.gpts_memory.app_link_chat_message("test123"))
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())