Skip to content

[WIP] Add core configuration for Aliyun integration#1

Draft
Copilot wants to merge 1 commit intomainfrom
copilot/add-core-configuration
Draft

[WIP] Add core configuration for Aliyun integration#1
Copilot wants to merge 1 commit intomainfrom
copilot/add-core-configuration

Conversation

Copy link

Copilot AI commented Feb 26, 2026

Thanks for asking me to work on this. I will get started on it and keep this PR's description up to date as I form a plan and make progress.

import os
import lancedb
import warnings
from typing import Type
from pydantic import BaseModel, Field

屏蔽掉 Pydantic 和 Deprecation 的刷屏警告

warnings.filterwarnings("ignore")

from crewai import Agent, Task, Crew, Process

导入基础工具类

from langchain.tools import BaseTool
from langchain_community.chat_models import ChatOpenAI
from langchain_huggingface import HuggingFaceEmbeddings
from crewai_tools import DirectoryReadTool

==========================================

1. 核心配置:直连阿里云

==========================================

ALIYUN_API_KEY = "你的_API_KEY" # ⚠️ 请确保填入真实 Key
os.environ["OPENAI_API_KEY"] = ALIYUN_API_KEY
BASE_URL = "https://coding.dashscope.aliyuncs.com/v1"

def get_model(name, temp=0.3):
return ChatOpenAI(
model=name,
openai_api_base=BASE_URL,
openai_api_key=ALIYUN_API_KEY,
temperature=temp
)

定义各个专家的大脑

llm_boss = get_model("glm-5")
llm_reader = get_model("qwen3.5-plus", 0.1)
llm_logic = get_model("qwen3-coder-plus", 0.2)
llm_critic = get_model("qwen3.5-plus", 0.4)

==========================================

2. 定义工具参数校验模型 (Pydantic 喜欢这个)

==========================================

class SearchInput(BaseModel):
query: str = Field(description="需要在私有库检索的关键词或短语")

==========================================

3. 将函数转化为正式的 BaseTool 类

==========================================

class MyLanceDBTool(BaseTool):
name: str = "LanceDB_Search"
description: str = "用于检索实验室私有知识库,获取文献细节、实验方案或历史数据。"
args_schema: Type[BaseModel] = SearchInput

def _run(self, query: str) -> str:
    """这是工具执行的核心逻辑"""
    try:
        LANCEDB_DIR = "/home/reny29/lancedb_data"
        db = lancedb.connect(LANCEDB_DIR)
        
        # 兼容性检查:确保表存在
        if "lab_knowledge" not in db.table_names():
            return "提示:私有数据库尚未构建,请先运行 ingest_data.py。"
        
        table = db.open_table("lab_knowledge")
        
        # 本地向量化
        embed = HuggingFaceEmbeddings(model_name="BAAI/bge-small-zh-v1.5")
        q_vec = embed.embed_query(query)
        
        # 搜索
        res = table.search(q_vec).limit(3).to_pandas()
        if res.empty: return "未找到匹配记录。"
        
        return "\n".join(res['text'].astype(str).tolist())
    except Exception as e:
        return f"搜索工具运行异常: {e}"

实例化工具

lancedb_tool = MyLanceDBTool()
local_paper_tool = DirectoryReadTool(directory_path="/home/reny29/papers")

==========================================

4. 重新构建 Agent 团队

==========================================

scientist = Agent(
role='医学机制科学家',
goal='结合本地文献挖掘分子靶点',
backstory='你是一个极其严谨、重视证据的科学家。',
llm=llm_reader,
tools=[local_paper_tool, lancedb_tool], # 现在是标准的 Tool 实例了
verbose=True,
allow_delegation=False
)

methodologist = Agent(
role='统计方法专家',
goal='设计严谨的数据分析方案',
backstory='你擅长处理高维组学数据和构建复杂模型。',
llm=llm_logic,
verbose=True,
allow_delegation=False
)

reviewer = Agent(
role='独立审核专家',
goal='指出方案逻辑硬伤',
backstory='你以尖锐、专业的审稿意见著称。',
llm=llm_critic,
verbose=True,
allow_delegation=False
)

director = Agent(
role='实验室总监 (PI)',
goal='输出可落地的科研手册',
backstory='你统筹全局,提升课题的医学价值。',
llm=llm_boss,
verbose=True,
allow_delegation=False
)

==========================================

5. 启动任务

==========================================

if name == "main":
print("\n🚀 [Aliyun Team] 正在尝试唤醒专家团队...")
topic = input("👩‍🔬 [PI reny29] 请输入今日科研探索方向:\n> ")

tasks = [
    Task(description=f"基于本地知识库,分析【{topic}】的核心分子机制。", expected_output="机制分析报告", agent=scientist),
    Task(description="为该课题设计统计学和 AI 算法验证方案。", expected_output="技术方案", agent=methodologist),
    Task(description="对上述内容进行 Peer Review,找出漏洞并提出修改。", expected_output="评审意见", agent=reviewer),
    Task(description="汇总定稿最终的科研执行计划书。", expected_output="最终版执行计划书", agent=director)
]

crew = Crew(
    agents=[scientist, methodologist, reviewer, director],
    tasks=tasks,
    process=Process.sequential
)

result = crew.kickoff()
print("\n" + "="*50 + "\n🏆 最终科研执行计划书:\n" + "="*50)
print(result)

这个code现在报错
(openclaw-env) reny29@DESKTOP-88GMTT4:~/medical_research_agents$ python research_team.py
/home/reny29/medical_research_agents/research_team.py:24: LangChainDeprecationWarning: The class ChatOpenAI was deprecated in LangChain 0.0.10 and will be removed in 1.0. An updated version of the class exists in the :class:~langchain-openai package and should be used instead. To use it run pip install -U :class:~langchain-openai and import as from :class:langchain_openai import ChatOpenAI``.
  return ChatOpenAI(
Traceback (most recent call last):
  File "/home/reny29/medical_research_agents/research_team.py", line 82, in
    scientist = Agent(
  File "/home/reny29/miniforge3/envs/openclaw-env/lib/python3.10/site-packages/pydantic/main.py", line 253, in init
    validated_self = self.pydantic_validator.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for Agent
tools.1
  Input should be a valid dictionary or instance of BaseTool [type=model_type, input_value=MyLanceDBTool(), input_type=MyLanceDBTool]
    For further information visit https://errors.pydantic.dev/2.11/v/model_type
(openclaw-env) reny29@DESKTOP-88GMTT4:
/medical_research_agents$
如何修改呢


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants