跳至内容
Hello Agent

Hello Agent

Hello Agent 笔记

环境与基础工具

openai用于大模型交互,提供接口范式(self.client = OpenAI(api_key=apiKey, base_url=baseUrl, timeout=timeout)),python-dotenv用于安全管理环境变量如密钥。

项目根目录下建 .env 文件

1
2
3
4
# .env file
LLM_API_KEY="YOUR-API-KEY"
LLM_MODEL_ID="YOUR-MODEL"
LLM_BASE_URL="YOUR-URL"

定义专属的LLM客户端类,封装交互细节

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

class HelloAgentsLLM:
    def __init__(self, model: str = None, apiKey: str = None, baseUrl: str = None, timeout: int = None):
        self.model = model or os.getenv("LLM_MODEL_ID")
        self.apiKey = apiKey or os.getenv("LLM_API_KEY")
        self.baseUrl = baseUrl or os.getenv("LLM_BASE_URL")
        self.timeout = timeout or int(os.getenv("LLM_TIMEOUT", 59))
        
        if not all([self.model, self.apiKey, self.baseUrl]):
            raise ValueError("模型、密钥、服务地址需在.env中提供")
        
        self.client = OpenAI(api_key = apiKey, base_url = baseUrl, timeout = timeout)
    
	def think():
        # 就是call llm操作
        print(f"🧠 正在调用 {self.model} 模型...")
        try:
            response = self.client.chat.completions.create(....)
            
            # 处理流式响应
            print("✅ 大语言模型响应成功:")
            collected_content = []
            for chunk in response:
                content = chunk.choices[0].delta.content or ""
                print(content, end="", flush=True)
                collected_content.append(content)
            print()  # 在流式输出结束后换行
            return "".join(collected_content)
        except Exception as e:
            print(f"报错{e}")
            return None
        
最后更新于