import requests
import pandas as pd
from spacy import load
nlp = load("en_core_web_sm")
class PerceptionLayer:
def __init__(self, api_url: str):
self.api_url = api_url
def fetch_structured_data(self, params: dict) -> pd.DataFrame:
response = requests.get(self.api_url, params=params, timeout=10)
response.raise_for_status()
return pd.DataFrame(response.json()["data"])
def extract_key_info(self, text: str) -> dict:
doc = nlp(text)
entities = {
"organizations": [ent.text for ent in doc.ents if ent.label_ == "ORG"],
"dates": [ent.text for ent in doc.ents if ent.label_ == "DATE"],
"numbers": [ent.text for ent in doc.ents if ent.label_ == "NUM"]
}
return entities
if __name__ == "__main__":
perception = PerceptionLayer("https://api.example.com/financial-data")
data = perception.fetch_structured_data({"start_date": "2024-01-01", "end_date": "2024-12-31"})
print("结构化数据采样:")
print(data.head())
text = "ABC 公司 2024 年 Q3 营收 120 亿元,同比增长 15%"
key_info = perception.extract_key_info(text)
print("\n关键信息抽取结果:")
print(key_info)
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from llama_cpp import Llama
llm = Llama(
model_path="./llama-2-7b-chat.ggmlv3.q4_0.bin",
n_ctx=2048,
n_threads=8
)
class DecisionLayer:
def __init__(self, llm):
self.llm = llm
self.decomposition_prompt = PromptTemplate(
input_variables=["goal"],
template="""请将以下复杂目标拆分为 3-5 个可执行的子任务,要求每个子任务明确、具体、可落地:
目标:{goal}
子任务列表(按执行顺序排列):
1.
2.
3.
4.
5."""
)
self.decomposition_chain = LLMChain(llm=llm, prompt=self.decomposition_prompt)
def decompose_goal(self, goal: str) -> list:
result = self.decomposition_chain.run(goal)
subtasks = [
line.strip().lstrip("0123456789.- ")
for line in result.split("\n")
if line.strip() and line.strip()[0].isdigit()
]
return subtasks
def adjust_priority(self, subtasks: list, urgency: float, importance: float) -> list:
"""
urgency: 紧急程度(0-1),importance: 重要程度(0-1)
优先级得分 = urgency * 0.4 + importance * 0.6
"""
import random
task_scores = [
(task, random.uniform(0, 1) * 0.4 + random.uniform(0, 1) * 0.6)
for task in subtasks
]
sorted_tasks = [
task for task, score in sorted(task_scores, key=lambda x: x[1], reverse=True)
]
return sorted_tasks
if __name__ == "__main__":
decision = DecisionLayer(llm)
goal = "完成 2024 年 Q3 财务报表分析,生成可视化报告并提出 3 条优化建议"
subtasks = decision.decompose_goal(goal)
print("目标拆解结果:")
for i, task in enumerate(subtasks, 1):
print(f"{i}. {task}")
sorted_tasks = decision.adjust_priority(subtasks, 0.7, 0.9)
print("\n优先级调整后:")
for i, task in enumerate(sorted_tasks, 1):
print(f"{i}. {task}")
import redis
from pymilvus import connections, Collection
import pandas as pd
import matplotlib.pyplot as plt
class MemoryLayer:
def __init__(self):
self.short_term_memory = redis.Redis(host="localhost", port=6379, db=0)
connections.connect("default", host="localhost", port="19530")
self.long_term_memory = Collection("agent_knowledge")
def store_short_term(self, task_id: str, data: dict):
self.short_term_memory.hset(task_id, mapping=data)
def get_short_term(self, task_id: str) -> dict:
return self.short_term_memory.hgetall(task_id)
def store_long_term(self, knowledge: str, embedding: list):
self.long_term_memory.insert([[knowledge], [embedding]])
class ExecutionLayer:
def __init__(self, memory: MemoryLayer):
self.memory = memory
def process_data(self, data: pd.DataFrame, task_id: str) -> pd.DataFrame:
data["revenue_growth"] = data["revenue"].pct_change() * 100
self.memory.store_short_term(task_id, {"processed_data": data.to_json()})
return data
def generate_visualization(self, data: pd.DataFrame, save_path: str):
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.plot(data["date"], data["revenue"], marker="o", linewidth=2)
plt.title("2024 Q3 Revenue Trend", fontsize=14)
plt.xlabel("Date")
plt.ylabel("Revenue (100M RMB)")
plt.xticks(rotation=45)
plt.subplot(1, 2, 2)
plt.bar(data["date"][1:], data["revenue_growth"][1:], color="green", alpha=0.7)
plt.title("Revenue Growth Rate", fontsize=14)
plt.xlabel("Growth Rate (%)")
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig(save_path, dpi=300, bbox_inches="tight")
return save_path
if __name__ == "__main__":
memory = MemoryLayer()
execution = ExecutionLayer(memory)
mock_data = pd.DataFrame({
"date": ["2024-07-01", "2024-08-01", "2024-09-01"],
"revenue": [100, 115, 120],
"cost": [60, 65, 70]
})
task_id = "task_2024_q3_finance"
processed_data = execution.process_data(mock_data, task_id)
print("数据处理结果:")
print(processed_data)
img_path = "./revenue_analysis.png"
execution.generate_visualization(processed_data, img_path)
print(f"\n可视化报告已保存至:{img_path}")