保姆教程:基于Copilot构建AI Agent

Agent 到底是什么

AI Agent 的经典定义是:一个能够通过传感器感知环境,并通过执行器对环境施加影响的实体。

在现代 AI 语境下,Agent 通常以大型语言模型(LLM)作为其思考核心,并借助代码架构来增强其规划、记忆等能力。其核心本质在于,用代码的确定性与可控性,来弥补大模型的不确定性及知识盲区。因此,我们可以在 Python 中设计 Agent 的完整运转流程,处理数据,并调用 Copilot 的接口来完成推理任务。

本文将介绍如何从零开始搭建一个基于 Copilot 的 AI Agent

文章目录

环境准备

1.Copilot Token 获取

Copilot Token 的获取方法:

1.登录GitHub

2.进入Setting界面,点击左侧的Developer Settings

3.personal access tokens 下拉框中选择 fine-grained token

4.点击Generate New Token

5.填写token name一栏(随便填)并选择copilot的权限

生成好的token在后续代码中会用到

2.安装Copilot SDK

安全起见,建议创建虚拟环境后在虚拟环境中安装sdk

bash 复制代码
python -m venv venv && source venv/bin/activate
pip install github-copilot-sdk

3.调用Copilot接口

创建main.py如下

python 复制代码
import asyncio
from copilot import CopilotClient, SubprocessConfig
from copilot.session import PermissionHandler

async def main():
    config = SubprocessConfig(github_token="your token")
    client = CopilotClient(config)
    await client.start()
    #创建session
    session = await client.create_session(on_permission_request=PermissionHandler.approve_all,model= "gpt-4.1")
    #查询请求
    response = await session.send_and_wait(prompt="用C++ 写一个Hello word程序")
    
    print(response.data.content)
    
    await client.stop()

asyncio.run(main())

其中your token 就是刚刚在Github上生成的token

运行程序

bash 复制代码
python main.py

输出结果如下:

4.构建Agent

当前的代码仅仅是向AI模型发送一个查询请求,然后接收响应。接下来我们要为它添加上下文记忆功能和循环处理的逻辑

python 复制代码
import asyncio
from copilot import CopilotClient, SubprocessConfig
from copilot.session import PermissionHandler

class SimpleAgent:
    def __init__(self):
        self.client = None
        self.session = None
        self.conversation_history = []
        
    async def initialize(self):
        config = SubprocessConfig(github_token="your token")
        self.client = CopilotClient(config)
        await self.client.start()
        
        self.session = await self.client.create_session(
            on_permission_request=PermissionHandler.approve_all,
            model="gpt-4.1"
        )
    
    async def process_task(self, task):
        # 创建包含历史记录的消息上下文
        # 只取最近的100条消息,防止超出上下文长度限制
        recent_history = self.conversation_history[-100:]
        
        # 构建完整的提示,包含历史记录
        context_messages = []
        for msg in recent_history:
            role = msg["role"]
            content = msg["content"]
            context_messages.append(f"{role.capitalize()}: {content}")
        
        # 添加当前任务
        context_messages.append(f"User: {task}")
        context_messages.append("Assistant:")  # 提示AI继续回应
        
        # 将上下文组合成一个字符串
        full_context = "\n".join(context_messages)
        
        # 发送带有上下文的请求
        response = await self.session.send_and_wait(prompt=full_context)
        response_content = response.data.content
        
        # 更新对话历史
        self.conversation_history.append({"role": "user", "content": task})
        self.conversation_history.append({"role": "assistant", "content": response_content})
        
        return response_content
    
    async def run_conversation(self):
        while True:
            user_input = input("请输入问题 (输入 'quit' 退出): ")
            if user_input.lower() == 'quit':
                break
            
            response = await self.process_task(user_input)
            print(f"AI: {response}")
    
    async def cleanup(self):
        if self.client:
            await self.client.stop()

# 使用示例
async def main():
    agent = SimpleAgent()
    await agent.initialize()
    await agent.run_conversation()
    await agent.cleanup()

asyncio.run(main())

运行代码输出如下:

在process_task 函数中,后续我们可以添加更多功能来处理用户输入或模型的输出来构建使用不同场景的agent。

相关推荐
奈落242 分钟前
AI 办公助手选型指南:从聊天问答到主动式工作流,企业办公自动化该怎么挑、边界在哪
人工智能·自动化·工作流·ai 办公
正经人_x5 分钟前
学习日记59:PAVL
人工智能·学习·计算机视觉
MacroZheng5 分钟前
这可能是Windows下最适合Claude Code/Codex的终端了,真的夯!
人工智能·后端·ai编程
还是奇怪5 分钟前
GPT-6 Sol 与 Luna 发布后,选型还要确认什么?从官方参数到迁移验证
人工智能·gpt·openai
WindrunnerMax10 分钟前
以轻量 LoopAgent 替代 RAG 实现文档检索
人工智能·架构·github
XMAIPC_Robot12 分钟前
FPGA+ARM联合调试避坑:储能电力采样数据同步、丢包问题定位与根治方案,应用于储能EMS、微网控制器中
arm开发·人工智能·fpga开发·rk3588+fpga·rk3576+fpga
AI浩14 分钟前
面向视觉预训练的对象级自蒸馏
人工智能·计算机视觉
天远Date Lab14 分钟前
零信任架构实战:基于天远风控经营异常预警构建自动化商业园区租户巡检网关
大数据·人工智能·架构·自动化
是翎15 分钟前
无障碍自动扫描:不只是一个分数
人工智能
临床数据科学和人工智能兴趣组15 分钟前
自定义缩放范围在数据分析中的应用也不少,尤其是在处理特定类型的数据时
人工智能·数据挖掘·数据分析·r语言·r语言-4.2.1