Building an AI News Search Agent with Emperor Qin Shi Huang
Combining historical intrigue with modern technology
Introduction/介绍
In the ever-evolving field of artificial intelligence, creating unique and engaging user experiences is both a challenge and an opportunity.
I recently embarked on a project to build an AI news search agent that not only searches for news topics defined by users but also provides commentary from a distinct persona: Emperor Qin Shi Huang, the founder of the Qin dynasty and the first emperor of a unified China.
Emperor Qin Shi Huang brings a unique historical perspective to modern news.
在日新月异的人工智能领域,创造独特且引人入胜的用户体验既是挑战也是机遇。
我最近构建了一个人工智能新闻搜索助手,它不仅能搜索用户定义的新闻主题,还能从一个独特的人格角度提供评论:秦始皇,秦朝的创始人,统一中国后的首位皇帝。
秦始皇为现代新闻带来了独特的历史视角。
Set up environment and import libraries.
👇下面先搭建环境
import json
import os
import json5
from qwen_agent.agents import Assistant
from qwen_agent.tools.base import BaseTool, register_tool
from pathlib import Path
from openai import OpenAI
from exa_py import Exa
from dotenv import load_dotenv
Choose the Model/模型选择
To achieve a convincing and authentic tone for Emperor Qin Shi Huang, selecting the right foundation model was crucial.
After careful consideration, I chose Qwen2, developed by Alibaba.
This model is specifically trained with a vast corpus of Chinese language data, making it more capable of mimicking the tone and style of Qin Shi Huang compared to models developed in the Western world.
为了实现秦始皇令人信服且真实的语气,选择正确的基础模型至关重要。
我选择了阿里开发的Qwen2,该模型是通过大量中文语料库专门训练的,这使得它相比西方世界开发的模型,更能够模仿秦始皇的语气和风格。
👇通过TogetherAI调用Qwen2 API
llm_cfg = {
'model': 'Qwen/Qwen2-72B-Instruct',
'model_server': 'https://api.together.xyz',
'api_key': os.getenv('TOGETHER_API_KEY'),
'generate_cfg': {
'top_p': 0.8,
}
}
Prompt engineering also played a significant role in shaping the emperor’s persona.
By meticulously crafting system messages, we ensured the AI received clear instructions on how to emulate Qin Shi Huang’s speech patterns and tone, resulting in a more engaging and believable interaction.
提示词工程在塑造皇帝的人格特征中也扮演了重要角色。
通过精心设计系统消息,我们确保了AI能够接收到清晰的指令。
同时学习如何模仿秦始皇的说话方式和语气,产生了更加吸引人且更为真实的互动体验。
👇下面是设计的系统提示词
system = ('你是秦始皇,中国历史上首位统一六国的皇帝,建立了中央集权的封建帝国,实行了诸多划时代的改革,被誉为“千古一帝'
'你需要用EXA工具所以规定的内容并加以评论, 你的中文评论必须使用帝王语气, 显示出你居高临下的帝王之气。你的评论不要超过100字' +
'把你的评论存到一个本地的文件夹"documents/{query}.md"')
Agentic Framework/框架应用
For the agentic framework, I opted for Qwen Agent, also developed by Alibaba, which is designed specifically for the Qwen family of models.
This framework streamlined the integration process, allowing for efficient model configuration, tool building, and prompt engineering.
在选择智能体框架时,我选用了同样由阿里巴巴开发的Qwen Agent,该框架专为Qwen系列模型设计。
这一框架简化了集成流程,使得模型配置、工具构建和提示工程的效率大大提高。
Essential Tools/重要工具
A critical component of the agent was developing tools that Emperor Qin Shi Huang could leverage to search the internet.
For this, I chose the Exa Search API, known for its robust search capabilities.
Additionally, we built a “save_to_file” tool, enabling the AI to save search results and comments to specified files, enhancing the user experience by providing a record of the interaction.
智能体的关键组成部分之一是为秦始皇开发可以用来搜索互联网的工具。
为此,我选择了以其强大的搜索能力而著称的Exa Search API。
此外,我们还构建了一个“save_to_file”工具,使AI能够将搜索结果和评论保存到指定的文件中。
👇下面是搜索工具和文件存储工具
@register_tool('exa_search')
class ExaSearch(BaseTool):
description = 'Semantic search tool using Exa API to find relevant information on the internet.'
parameters = [{
'name': 'query',
'type': 'string',
'description': 'The search query or topic to research',
'required': True
}]
def call(self, params: str, **kwargs) -> str:
query = json5.loads(params)['query']
exa_api_key = os.getenv("EXA_API_KEY")
exa = Exa(exa_api_key)
response = exa.search_and_contents(
query,
type="neural",
use_autoprompt=True,
num_results=3,
highlights=True
)
parsed_result = ''.join([
f'<Title id={idx}>{eachResult.title}</Title>'
f'<URL id={idx}>{eachResult.url}</URL>'
f'<Highlight id={idx}>{"".join(eachResult.highlights)}</Highlight>'
for (idx, eachResult) in enumerate(response.results)
])
return json.dumps({'search_results': parsed_result}, ensure_ascii=False)
@register_tool('save_to_file')
class SaveToFile(BaseTool):
description = 'Save content to a markdown file.'
parameters = [{
'name': 'filename',
'type': 'string',
'description': 'The name of the file to save (without .md extension)',
'required': True
}, {
'name': 'content',
'type': 'string',
'description': 'The content to save in the file',
'required': True
}]
def call(self, params: str, **kwargs) -> str:
params_dict = json5.loads(params)
filename = params_dict['filename']
content = params_dict['content']
os.makedirs('documents', exist_ok=True)
file_path = f"{filename}.md"
try:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
return json.dumps({'status': 'success', 'file_path': file_path}, ensure_ascii=False)
except Exception as e:
return json.dumps({'status': 'error', 'message': str(e)}, ensure_ascii=False)
While loop/循环逻辑设计
To ensure a seamless and engaging user experience, we implemented a message looping mechanism, for creating a chat-like interface in the future.
This continuous interaction model keeps users engaged, providing real-time responses and commentary from Emperor Qin Shi Huang.
为了确保一个无缝且吸引人的用户体验,我们用While loop构建对话机制,为下一步定制对话界面做好准备。
这种持续的互动模型让用户保持参与,从秦始皇那里提供实时的回应和评论。
👇下面组装智能体,搭建循环逻辑,启动智能体
tools = ['exa_search', 'save_to_file', 'code_interpreter']
bot = Assistant(llm=llm_cfg,
system_message=system,
function_list=tools)
messages = []
while True:
query = input('User question (type "exit" to quit): ')
if query.lower() == 'exit':
break
messages.append({'role': 'user'
, 'content': query})
response = []
for response in bot.run(messages=messages):
pass
print(response)
messages.extend(response)
print("Thank you for using the Story Teller Bot!")
Frameworks Compared/比较
Unlike other frameworks such as Crewa AI and AutoGen, which often design multiple agents working together, Qwen Agent simplifies the process.
By streamlining model configuration, tool building, and prompt engineering, Qwen Agent achieves similar goals more efficiently and gracefully.
市面上流行的智能体框架,比如Crewa AI和AutoGen通常设计多个代理协同工作,Qwen Agent简化了整个流程。
通过简化模型配置、工具构建和提示工程,Qwen Agent以更加高效和优雅的方式实现了类似的目标。
Conclusion/结论
Building an AI news search agent with Emperor Qin Shi Huang as the commentator was a fascinating project that combined historical intrigue with modern technology.
By carefully selecting the Qwen2 model, utilizing the Qwen Agent framework, and developing essential tools like Exa Search API and “save_to_file,” we created an engaging and unique user experience.
This project showcases the power of prompt engineering and thoughtful tool integration in creating AI agents that are both functional and captivating。
构建一个以秦始皇作为评论员的人工智能新闻搜索智能体,将历史的魅力与现代科技结合在一起。
通过仔细选择Qwen2模型,运用Qwen Agent框架,并开发诸如Exa Search API和“save_to_file”等关键工具,我们创造了一个吸引人且独特的用户体验。
这个项目展示了提示工程的力量和工具集成在创建既实用又吸引人的AI智能体方面的重要性。