import os
import asyncio
import datetime
from typing importAnyfrom dataclasses import dataclass
import nest_asyncio
nest_asyncio.apply()
from openai import AsyncOpenAI
from pydantic_ai.models.openai import OpenAIModel
import streamlit as st
from pydantic_ai import Agent, RunContext
from pydantic import BaseModel, Field
from tavily import AsyncTavilyClient
from dotenv import load_dotenv
load_dotenv() # 加载环境变量
四、模型与 API 配置
1. 设置 LLM 提供者
Pydantic 直接与 OpenAI、Groq 和 VertexAI 配合使用。但在本教程中,我们将使用 Ollama,它现在与 OpenAI Chat Completions API 内置兼容,使得可以在本地使用更多工具和应用程序,无需支付 API 费用。
search_agent = Agent(
model,
deps_type=ResearchDependencies,
result_type=ResearchResult,
system_prompt='You are a helpful research assistant, you are an expert in research. ''When given a query, you will identify strong keywords to do 3-5 searches using the provided search tool. ''Then combine results into a detailed response.'
)
@search_agent.system_promptasyncdefadd_current_date(ctx: RunContext[ResearchDependencies]) -> str:
todays_date = ctx.deps.todays_date
system_prompt = (
f"You're a helpful research assistant and an expert in research. "f"When given a question, write strong keywords to do 3-5 searches in total "f"(each with a query_number) and then combine the results. "f"If you need today's date it is {todays_date}. "f"Focus on providing accurate and current information."
)
return system_prompt
st.set_page_config(page_title="AI News Researcher", layout="centered")
st.title("Large Language Model News Researcher")
st.write("Stay updated on the latest trends and developments in Large Language Model.")
## User input section
st.sidebar.title("Search Parameters")
query = st.sidebar.text_input("Enter your query:", value="latest Large Language Model news")
max_results = st.sidebar.slider("Number of search results:", min_value=3, max_value=10, value=5)
st.write("Use the sidebar to adjust search parameters.")
if st.button("Get Latest Large Language Model News"):
with st.spinner("Researching, please wait..."):
try:
result_data = asyncio.run(do_search(query, max_results))
st.markdown(result_data.research_title)
# A bit of styling for the main article
st.markdown(f"<div style='line-height:1.6;'>{result_data.research_main}</div>", unsafe_allow_html=True)
st.markdown("### Key Takeaways")
st.markdown(result_data.research_bullets)
except Exception as e:
st.error(f"An error occurred during research: {e}")