Wendong-Fan commited on
Commit
f597cc4
·
2 Parent(s): 7ff529c b0ecc50

Community Usecase - learning assistant (#374)

Browse files
community_usecase/learning-assistant/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Learning Assistant
2
+
3
+ This code example searches the internet for relevant learning materials depending on the user's knowledge level and devises a concrete learning roadmap all tailored to the user.
4
+
5
+ ## How to use
6
+
7
+ 1. Set up the OPENAI api key in the .env file
8
+
9
+ ```bash
10
+ OPENAI_API_KEY = 'xxx'
11
+ ```
12
+
13
+ 2. Copy the python script to the owl/examples folder.
14
+
15
+ 3. Run the script
16
+
17
+ ```bash
18
+ python run_gpt4o.py
19
+ ```
20
+
21
+ 4. You can find the entire thought process of the agent within the log file.
22
+
23
+ 5. Video demo - https://drive.google.com/drive/folders/1msrNNwjeZ0DKhSXCi2w1ljz_hULSusa_?usp=sharing
community_usecase/learning-assistant/run_gpt4o.py ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import json
4
+
5
+ from dotenv import load_dotenv
6
+ from camel.models import ModelFactory
7
+ from camel.types import ModelPlatformType
8
+
9
+ from camel.toolkits import (
10
+ SearchToolkit,
11
+ BrowserToolkit,
12
+ )
13
+ from camel.societies import RolePlaying
14
+ from camel.logger import set_log_level, get_logger
15
+
16
+ import pathlib
17
+
18
+ base_dir = pathlib.Path(__file__).parent.parent
19
+ env_path = base_dir / "owl" / ".env"
20
+ load_dotenv(dotenv_path=str(env_path))
21
+
22
+ set_log_level(level="DEBUG")
23
+ logger = get_logger(__name__)
24
+ file_handler = logging.FileHandler("learning_journey.log")
25
+ file_handler.setLevel(logging.DEBUG)
26
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
27
+ file_handler.setFormatter(formatter)
28
+ logger.addHandler(file_handler)
29
+
30
+ root_logger = logging.getLogger()
31
+ root_logger.addHandler(file_handler)
32
+
33
+
34
+ def construct_learning_society(task: str) -> RolePlaying:
35
+ """Construct a society of agents for the learning journey companion.
36
+
37
+ Args:
38
+ task (str): The learning task description including what the user wants to learn and what they already know.
39
+
40
+ Returns:
41
+ RolePlaying: A configured society of agents for the learning companion.
42
+ """
43
+ models = {
44
+ "user": ModelFactory.create(
45
+ model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
46
+ model_type="gpt-4o",
47
+ api_key=os.getenv("OPENAI_API_KEY"),
48
+ model_config_dict={"temperature": 0.4},
49
+ ),
50
+ "assistant": ModelFactory.create(
51
+ model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
52
+ model_type="gpt-4o",
53
+ api_key=os.getenv("OPENAI_API_KEY"),
54
+ model_config_dict={"temperature": 0.4},
55
+ ),
56
+ "content_researcher": ModelFactory.create(
57
+ model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
58
+ model_type="gpt-4o",
59
+ api_key=os.getenv("OPENAI_API_KEY"),
60
+ model_config_dict={"temperature": 0.2},
61
+ ),
62
+ "planning": ModelFactory.create(
63
+ model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,
64
+ model_type="gpt-4o",
65
+ api_key=os.getenv("OPENAI_API_KEY"),
66
+ model_config_dict={"temperature": 0.3},
67
+ ),
68
+ }
69
+
70
+ browser_toolkit = BrowserToolkit(
71
+ headless=False,
72
+ web_agent_model=models["content_researcher"],
73
+ planning_agent_model=models["planning"],
74
+ )
75
+
76
+ tools = [
77
+ *browser_toolkit.get_tools(),
78
+ SearchToolkit().search_duckduckgo,
79
+ ]
80
+
81
+ user_agent_kwargs = {
82
+ "model": models["user"],
83
+ }
84
+
85
+ assistant_agent_kwargs = {
86
+ "model": models["assistant"],
87
+ "tools": tools,
88
+
89
+ }
90
+
91
+ task_kwargs = {
92
+ "task_prompt": task,
93
+ "with_task_specify": False,
94
+ }
95
+
96
+ society = RolePlaying(
97
+ **task_kwargs,
98
+ user_role_name="learner",
99
+ user_agent_kwargs=user_agent_kwargs,
100
+ assistant_role_name="learning_companion",
101
+ assistant_agent_kwargs=assistant_agent_kwargs,
102
+ )
103
+
104
+ return society
105
+
106
+
107
+ def analyze_chat_history(chat_history):
108
+ """Analyze chat history and extract tool call information."""
109
+ print("\n============ Tool Call Analysis ============")
110
+ logger.info("========== Starting tool call analysis ==========")
111
+
112
+ tool_calls = []
113
+ for i, message in enumerate(chat_history):
114
+ if message.get("role") == "assistant" and "tool_calls" in message:
115
+ for tool_call in message.get("tool_calls", []):
116
+ if tool_call.get("type") == "function":
117
+ function = tool_call.get("function", {})
118
+ tool_info = {
119
+ "call_id": tool_call.get("id"),
120
+ "name": function.get("name"),
121
+ "arguments": function.get("arguments"),
122
+ "message_index": i,
123
+ }
124
+ tool_calls.append(tool_info)
125
+ print(f"Tool Call: {function.get('name')} Args: {function.get('arguments')}")
126
+ logger.info(f"Tool Call: {function.get('name')} Args: {function.get('arguments')}")
127
+
128
+ elif message.get("role") == "tool" and "tool_call_id" in message:
129
+ for tool_call in tool_calls:
130
+ if tool_call.get("call_id") == message.get("tool_call_id"):
131
+ result = message.get("content", "")
132
+ result_summary = result[:100] + "..." if len(result) > 100 else result
133
+ print(f"Tool Result: {tool_call.get('name')} Return: {result_summary}")
134
+ logger.info(f"Tool Result: {tool_call.get('name')} Return: {result_summary}")
135
+
136
+ print(f"Total tool calls found: {len(tool_calls)}")
137
+ logger.info(f"Total tool calls found: {len(tool_calls)}")
138
+ logger.info("========== Finished tool call analysis ==========")
139
+
140
+ with open("learning_journey_history.json", "w", encoding="utf-8") as f:
141
+ json.dump(chat_history, f, ensure_ascii=False, indent=2)
142
+
143
+ print("Records saved to learning_journey_history.json")
144
+ print("============ Analysis Complete ============\n")
145
+
146
+
147
+ def run_learning_companion(task: str = None):
148
+ """Run the learning companion with the given task.
149
+
150
+ Args:
151
+ task (str, optional): The learning task description. Defaults to an example task.
152
+ """
153
+ task = """
154
+ I want to learn about the transformers architecture in an llm.
155
+ I've also taken a basic statistics course.
156
+ I have about 10 hours per week to dedicate to learning. Devise a roadmap for me .
157
+ """
158
+
159
+ society = construct_learning_society(task)
160
+
161
+ from owl.utils import run_society
162
+ answer, chat_history, token_count = run_society(society, round_limit = 5)
163
+
164
+ # Record tool usage history
165
+ analyze_chat_history(chat_history)
166
+ print(f"\033[94mAnswer: {answer}\033[0m")
167
+
168
+ if __name__ == "__main__":
169
+ run_learning_companion()