Ai Agent With Pydanticai And Mongodb
This project demonstrates how to build an intelligent information retrieval system that combines local vector search with real-time internet search capabilities. The system addresses a critical challenge in AI applications: providing accurate, up-to-date information while maintaining high performance and reliability.
Core Problem and Solution:
Traditional language models often provide outdated information, while pure internet search lacks semantic understanding. This hybrid RAG system solves this by combining a MongoDB vector database for historical tech news with real-time internet search through Tavily, ensuring both speed and freshness of information.
Real-World Applications:
-
Enterprise Intelligence: Companies like Microsoft or Google could use this to track competitor activities and market trends, combining historical data with breaking news.
-
Financial Analysis: Investment firms could monitor market movements and company developments, getting both archived research and current announcements about topics like "recent developments in EV technology."
-
Research Monitoring: Research institutions could track scientific developments, accessing both established research and recent breakthroughs in fields like quantum computing or AI.
What makes this implementation particularly powerful is its use of modern tools and practices:
- Pydantic provides robust type safety and validation
- PydanticAI for implementing ai agents with access to system tools
- MongoDB's vector search capabilities enable efficient semantic search
- Tavily for internet search and implementing HybridRAG
- The hybrid RAG approach combines the benefits of both local and internet search
- Dependency injection patterns make the system maintainable and testable
Glossary:
- Agents
- RAG
- Agentic RAG
- Control Flow
- HybridRAG
Step 1: Installing Libaries and Environment Variables
Let's break down why we need each of these packages:
pydantic-ai: This is our framework for building type-safe AI agents. It provides the scaffolding for creating reliable, maintainable AI applications with proper dependency injection and error handling.pymongo: Our interface to MongoDB, which will serve as both our vector database and operational data store. We'll use it to store and retrieve embeddings for semantic search.datasets: Hugging Face's datasets library, which we'll use to load our initial tech news dataset. This gives us a solid foundation of data to work with and use as the knowledge base for the agent.pandas: The Swiss Army knife of data manipulation in Python. We'll use it to process and transform our data before storage.tavily-python: A powerful search client that will enable our system to perform real-time internet searches, complementing our local vector search capabilities.
Note: As of the publshing of this notebook, PydanticAI is in early beta.
Enter your OpenAI API key: ··········
Step 2: Creating a Simple Agent with PydanticAI and OpenAI
The first major component we need to understand is the AI agent itself. This agent will be the orchestrator of our entire system, handling everything from query processing to result generation.
An agent is a computational entity composed of several integrated components, including the brain(llm), perception(environment) and action components(tools). These components work cohesively to enable the agent to achieve its defined objectives and goals.
Read more here
In modern Python applications, especially those dealing with AI and real-time data processing, we often work with asynchronous operations. However, when working in environments like Jupyter notebooks or when dealing with nested event loops, we can run into limitations with Python's default asyncio implementation.
The line nest_asyncio.apply() solves this by allowing nested event loops to run. Think of it like giving your code the ability to multitask within multitasking – it's essential for complex applications that need to handle multiple asynchronous operations simultaneously.
Pydantic AI Approach to Agents
When building AI applications, one of the most crucial components is managing interactions with language models in a structured, type-safe way. PydanticAI's Agent system provides exactly this, offering a robust framework for creating AI-powered applications.
A high level way of conceptualizing an Agent Agent() is to imagine a wrapper around an LLM model = OpenAIModel('gpt-4o') that converts the LLM into a system compoents with additional components such as:
- System Prompts: Instructions that guide the LLM's behavior
- Function Tools: Custom functions the LLM can call during execution
- Structured Result Types: Defined output formats
- Dependencies: Resources needed during execution
- Model Settings: Configuration for fine-tuning responses
We will talk more on dependencies and other components in later section of this notebook. But in the code above we pass the model and system_prompt arguments. These are the only component we need for a basic level Agent using Pydantic.
For our basic Agent, it will take a user input and then convert it into uppercase letters to simulate shouting
THIS SENTENCE STARTED OFF INITIALLY QUIETER!
There are three main ways to execute an agent in Pydantic AI:
-
agent.run(): This is used in asynchronous contexts where you want to await a single complete response. It returns a coroutine that resolves to a RunResult containing the agent's full response. Ideal for async web applications or when integrating with other async code. -
agent.run_sync(): This is used in synchronous contexts where you want a simple, blocking call that returns a complete response. It's essentially a wrapper around run() that handles the async/sync conversion for you. Perfect for scripts, notebooks, or synchronous applications where you need a straightforward way to get results. This is the one we use in the example above. -
agent.run_stream(): This is used when you want to receive the agent's response in chunks as they become available. It returns a StreamedRunResult that can be iterated over asynchronously, making it ideal for real-time applications, chat interfaces, or when dealing with long responses where you want to show progressive updates to users.
And that's how simple it is to build an Agent with Pydantic AI. It's very straightforward yet powerful, offering type safety, dependency injection(shown later), and flexible execution methods all in one package.
While the basic setup can be as simple as defining a model and system prompt, the framework scales elegantly to handle complex use cases like our hybrid RAG system.
The combination of Python's type system with PydanticAI's structured approach to AI agent development makes it an excellent choice for building production-ready AI applications that are both maintainable and reliable.
Next, let's give our Agent some knowledge.
Step 3: Data Loading and Preparation
One of the first steps in building a robust RAG system is establishing a solid knowledge base. Let's explore how to efficiently load and process data from Hugging Face's datasets library, specifically focusing on a tech news embeddings dataset.
To further enhance the dataset's utility, there is an e,embedding attribute for each data point that has a vector embedding created using the OpenAI EMBEDDING_MODEL = "text-embedding-3-small", with an EMBEDDING_DIMENSION of 256.
Resolving data files: 0%| | 0/42 [00:00<?, ?it/s]
The code snippet above retrieves data from the Hugging Face dataset repository, specifically, the MongnoDB tech_embeddings dataset available here.
-
Streaming Mode: By setting
streaming=True, we enable efficient memory handling for large datasets. Instead of loading everything at once, we can process data in chunks. -
Split Selection: Using
split="train"specifies which portion of the dataset we want to access. -
Memory Management:
ds.take(10000)allows us to work with a subset of data. You can increase this as you see fit. The limitation primarly prevents memory overflow issues with large datasets. The full tech embeddings dataset contains 1,576,528 data points.
Note: best practices for when working with datasets for RAG systems is to start small. Begin with a manageable subset to validate your pipeline and then incrementally increase size once core functionality is verified
PydanticAI is created by the team that made Pydantic, which we will use to ensure data integrity and type safety throughout our application.
Below we create a data model TechNewsData. This structured approach to data modeling helps prevent bugs early in the development process and makes your code more maintainable. As your RAG system grows, having these strong type guarantees becomes increasingly valuable.
The benefits of using Pydantic models in your RAG system are threefold:
-
you get robust type safety with automatic validation, clear contracts, and IDE autocompletion; serialization capabilities that make JSON conversion and MongoDB integration effortless while maintaining clean API interfaces;
-
and comprehensive documentation features including self-documenting code, clear field descriptions,
-
and automatic schema generation, all of which contribute to making your codebase more maintainable and developer-friendly.
Step 4: Defining Embedding Function
When building a RAG (Retrieval Augmented Generation) system, one of the fundamental components is converting text into vector embeddings. These embeddings allow us to perform semantic search, finding similar content based on meaning rather than just matching keywords. Let's look at how to implement this using OpenAI's embedding API.
Embeddings are generated from a list of string input as shown in the example below:
# Example usage in a real-world scenario
news_articles = [
"OpenAI releases GPT-5",
"New advancements in quantum computing",
"Latest developments in AI ethics"
]
The embedding model used is text-embedding-3-small, OpenAI's latest embedding model optimized for efficient semantic search and text similarity tasks. This model offers a good balance between performance and cost, making it suitable for RAG applications.
By setting a constant DIMENSION_SIZE, we ensure all our embeddings have consistent dimensions. This is crucial when working with vector databases and performing similarity searches. Consistent dimensions are essential because:
They enable efficient vector operations They ensure compatibility across your database They allow for predictable memory usage and indexing
The dimension size for this notebook is 256, which is relatively small, and for production scenarios, larger dimension sizes can be used to capture more semantics within the data.
When choosing dimension size, consider:
- Your specific use case requirements
- Available computational resources
- Storage capacity
- Query performance needs
- Cost considerations
For many applications, 256 dimensions provide a good starting point for prototyping and testing your RAG system before scaling up to larger dimensions in production.
Read these articles for more information on choosing embedding models and chunking stratgeies
Step 5: MongoDB (Operational and Vector Database)
MongoDB acts as both an operational and vector database for the RAG system. MongoDB Atlas specifically provides a database solution that efficiently stores, queries and retrieves vector embeddings.
Creating a database and collection within MongoDB is made simple with MongoDB Atlas.
- First, register for a MongoDB Atlas account. For existing users, sign into MongoDB Atlas.
- Follow the instructions. Select Atlas UI as the procedure to deploy your first cluster.
Follow MongoDB’s steps to get the connection string from the Atlas UI. After setting up the database and obtaining the Atlas cluster connection URI, securely store the URI within your development environment.
Enter your MONGO URI: ··········
Let's explore how to properly set up and manage MongoDB collections for our RAG system's knowledge base. This setup is crucial for storing and retrieving our vectorized news articles description+title efficiently.
Connection to MongoDB successful Collection 'knowledge_base' created successfully.
When building a RAG system, proper database setup is crucial for managing your knowledge base effectively.
Our implementation uses MongoDB, a general purpose database that's particularly well-suited for handling document-based data and vector embeddings.
The code snippet above establishes a connection to MongoDB through the get_mongo_client function, then sets up a database named "tech_news_agent" with a collection called "knowledge_base".
We implement a robust error-handling pattern that checks if the collection exists before attempting to create it, catching any CollectionInvalid exceptions that might occur during the process. This idempotent approach means the code can be run multiple times safely – if the collection already exists, it simply connects to it; if not, it creates it.
The clear naming conventions (like tech_news_agent for the database and knowledge_base for the collection) make the code's purpose immediately apparent and easier to maintain. Finally, we assign the collection to a knowledge_base variable, which we'll use throughout our application for storing and retrieving vectorized news articles. This foundation ensures our RAG system has a reliable and efficient data storage layer, ready for implementing vector search capabilities and managing our embedded documents.
Step 6: Data Ingestion
DeleteResult({'n': 0, 'electionId': ObjectId('7fffffff000000000000003a'), 'opTime': {'ts': Timestamp(1736447697, 1), 't': 58}, 'ok': 1.0, '$clusterTime': {'clusterTime': Timestamp(1736447697, 1), 'signature': {'hash': b'\x06\xb1\xdb^\xd2cP\xf5xs\xba\xc42x\x91\xf1\x862\x9bM', 'keyId': 7421923411288391683}}, 'operationTime': Timestamp(1736447697, 1)}, acknowledged=True) Why MongoDB for AI Workloads?
MongoDB, offers several compelling advantages for AI workloads, particularly in simplifying data ingestion.
The code snippet below demonstrates how MongoDB streamlines the data ingestion process by eliminating the need for explicit serialization and deserialization.
Data ingestion into MongoDB completed
##Step 7: Vector Search Index Creation
{'fields': [{'type': 'vector', 'path': 'embedding', 'numDimensions': 256, 'similarity': 'cosine'}]}
Creating index 'vector_index'... Waiting for 60 seconds to allow index 'vector_index' to be created... 60-second wait completed for index 'vector_index'.
'vector_index'
Step 8: Vector Search Operation
[{'companyName': '10Clouds',
'companyUrl': 'https://hackernoon.com/company/10clouds',
'description': 'Find insight on Aerojet Rocketdyne Appen and more in the '
'latest Market Talks covering Technology Media and Telecom.',
'published_at': '2023-03-17 10:52:00',
'score': 0.7128037214279175,
'title': 'Tech Media & Telecom Roundup: Market Talk',
'url': 'https://www.wsj.com/articles/tech-media-telecom-roundup-market-talk-8105659d'},
{'companyName': '10Clouds',
'companyUrl': 'https://hackernoon.com/company/10clouds',
'description': 'Find insight on LONGi Green Energy Technology Auto Trader '
'and more in the latest Market Talks covering the Technology '
'Media and Telecom sector.',
'published_at': '2023-06-01 11:07:00',
'score': 0.7083801031112671,
'title': 'Tech Media & Telecom Roundup: Market Talk',
'url': 'https://www.wsj.com/articles/tech-media-telecom-roundup-market-talk-8306f871'},
{'companyName': '10Clouds',
'companyUrl': 'https://hackernoon.com/company/10clouds',
'description': 'Find insight on Inari Amertron Xiaomi and more in the latest '
'Market Talks covering the Tech Media & Telecom sector.',
'published_at': '2023-09-01 19:52:00',
'score': 0.7066687941551208,
'title': 'Tech Media & Telecom Roundup: Market Talk',
'url': 'https://www.wsj.com/business/earnings/tech-media-telecom-roundup-market-talk-b499c47a'},
{'companyName': '10Clouds',
'companyUrl': 'https://hackernoon.com/company/10clouds',
'description': 'Find insight on Inari Amertron Xiaomi and more in the latest '
'Market Talks covering the Tech Media & Telecom sector.',
'published_at': '2023-09-01 19:52:00',
'score': 0.7066687941551208,
'title': 'Tech Media & Telecom Roundup: Market Talk',
'url': 'https://www.wsj.com/business/earnings/tech-media-telecom-roundup-market-talk-b499c47a'},
{'companyName': '10Clouds',
'companyUrl': 'https://hackernoon.com/company/10clouds',
'description': 'Find insight on Inari Amertron Xiaomi and more in the latest '
'Market Talks covering the Tech Media & Telecom sector.',
'published_at': '2023-09-01 09:48:00',
'score': 0.7066071033477783,
'title': 'Tech Media & Telecom Roundup: Market Talk',
'url': 'https://www.wsj.com/business/earnings/tech-media-telecom-roundup-market-talk-b499c47a'}]
Step 9: Creating PydanticAI Agents with Tools
Tools are a mechanim to extend an agents capabilities in ways that supersedes the limitation of instructions/information provided through system prompts.
Below are the key features of tools in PydanticAI
- Context Awareness: Tools can be either context-aware
(@agent.tool)or context-free(@agent.tool_plain) - Type Safety: Tools leverage Python's type hints for parameter validation
- Automatic Documentation: Function docstrings are automatically used to build tool schemas
- Flexible Registration: Tools can be registered via decorators or through the Agent constructor
There are three primary methods to create tools in PydanticAI:
-
Using
@agent.toolDecorator: Tools that need access to dependencies or context (like database connections, API clients). Ideal for most production scenarios where you need to manage resources or maintain state. -
Using
@agent.tool_plainDecorator: Best for: Stateless utilities or simple computations that don't require context or dependencies. Perfect for pure functions like calculations or text processing. -
Via the tools Parameter in Agent Constructor: Reusing existing functions as tools across different agents or when you need more control over tool configuration. Useful in scenarios where you're building multiple agents that share common functionality.
Each method trades off between simplicity and flexibility:
- Decorators offer the cleanest syntax and are most commonly used across other similar Agentic Frameworks
- Plain tools are perfect for simple, context-free operations
- Constructor injection provides the most flexibility for tool reuse and configuration
Choose based on your specific needs - whether you need context access, plan to reuse the tool, or prefer a certain style of code organization.
We will be implementing all three variaties in the section below
Connection to MongoDB successful
Here are some recent news articles on electric cars: 1. **SK signet Inks Deal with Francis Energy for the Supply of Ultra-Fast EV Chargers to the US** SK Signet has signed a deal with Francis Energy for an order of more than 1000 EV chargers. Francis Energy is currently the fourth-largest fast charger operator in the United States. [Read more](https://www.econotimes.com/SK-signet-Inks-Deal-with-Francis-Energy-for-the-Supply-of-Ultra-Fast-EV-Chargers-to-the-US-1659601) (Published on 2023-07-18) 2. **YS Tech working closely with China car vendors** Automotive cooling fan supplier Yen Sun Technology (YS Tech) is working closely with Chinese customers and anticipates a new Chinese government policy to boost the country's EV sector. [Read more](https://www.digitimes.com/news/a20230309PD211/automotive-china-ev+green-energy-ys-tech.html) (Published on 2023-03-10) 3. **Investing in Cleaner Technology: Lesser-Known Areas of Innovation to Watch** This article discusses cleaner energy investment opportunities in lesser-known areas of innovation that aim to bridge the gap between current technology and future needs for cleaner energy. [Read more](https://www.nasdaq.com/articles/investing-in-cleaner-technology%3A-lesser-known-areas-of-innovation-to-watch) (Published on 2023-01-30) These articles highlight some key developments and investments in the electric car sector and cleaner technologies.
Enter your Tavily API key: ··········
Collection 'working_memory' created successfully.
Creating index 'vector_index'... Waiting for 60 seconds to allow index 'vector_index' to be created... Error creating new vector search index 'vector_index': 'float' object has no attribute 'sleep'
DeleteResult({'n': 0, 'electionId': ObjectId('7fffffff000000000000003a'), 'opTime': {'ts': Timestamp(1736447917, 1), 't': 58}, 'ok': 1.0, '$clusterTime': {'clusterTime': Timestamp(1736447917, 1), 'signature': {'hash': b'Y\xd1\x15\xa32fD\x0fx\xaf\xbbp\x13\x19\xb1QR)~\xf7', 'keyId': 7421923411288391683}}, 'operationTime': Timestamp(1736447917, 1)}, acknowledged=True) [{'content': 'Photo Galleries\n'
'Most Popular\n'
'Motor Authority Newsletter\n'
'Sign up to get the latest performance and luxury automotive '
'news, delivered to your inbox daily!\n'
' Electric Cars\n'
'The AMG version of the EQE SUV doesn’t have the fire and fury of '
'other models from Mercedes’ performance arm.\n'
' Will the jump-started VW brand really bring out a new '
'Aristocrat, or is just protecting IP?\n'
'VW is working on an electric GTI but it might not be '
'Golf-based.\n'
' The 1,234-hp Lucid Air Sapphire is the quickest car ever to '
'grace the MA Best Car To Buy competition.\n'
' The 964 RSR is a dream car for 911 fans of a certain age, and '
'Everrati is looking to capitalize with an electric tribute.\n',
'origin': 'foreign',
'score': 0.7156829},
{'content': 'Electric Cars news & latest pictures from Newsweek.com Newsweek '
'pulls back the curtain on what goes has gone into developing '
"Rivian's electric vehicle charging network. U.S. Electric "
'vehicles improved but still less reliable than gas models: '
'survey Donald Trump is reportedly planning to scrap a $7,500 '
'federal consumer tax credit for electric vehicles. Gavin Newsom '
'prepared to challenge Trump on electric vehicle tax credits '
'Gavin Newsom prepared to challenge Trump on electric vehicle tax '
'credits Newsom proposes California offer state tax rebates for '
'electric vehicle purchases should Donald Trump eliminate the '
'federal EV tax credit. Getting rid of the federal rebate could '
'devastate the electric vehicle industry, but Tesla CEO Elon Musk '
"doesn't mind. U.S. awards $3 billion for EV battery production "
'to counter China',
'origin': 'foreign',
'score': 0.6617704},
{'content': 'Read the latest electric vehicle news, recent EV reviews and EV '
'buying advice at Cars.com.',
'origin': 'foreign',
'score': 0.6453216},
{'content': 'And Hard\n'
'The 2025 Honda CR-V e:FCEV Is A Hydrogen Plug-In Hybrid, For '
'Real\n'
'EV News\n'
'Filter by:\n'
'Why Is Motorcycle Racing Afraid Of This Electric Bike?\n'
'Chinese Cars Would Get 125% Price Increase Under New Senate '
'Bill\n'
'Watch Tesla Cybertruck Owner Shoot Bullets At His Truck With '
'Submachine Gun, Shotgun\n'
"'Mind-Blowing' Tesla Roadster Final Form To Debut But Then The "
'Story Got Weird\n'
'What Trump Got Wrong About EVs During His Michigan Speech\n'
"The Polestar 3 Can't Come Soon Enough\n"
'Tesla Arson Suspect Caught On Camera: Two Model Ys Burnt\n'
'FreeWire’s New Pro Series DC Fast Chargers Can Also Power Your '
'Business\n'
'Will Americans Buy This Tiny, Cute Electric Car?\n'
' It May Work\n'
"Watch Ford's 1,400-HP SuperVan Blast Its Way To Several Lap "
'Records At Bathurst\n'
'Electrification Leads To All-Wheel-Drive Dominance\n'
'BYD Brings Denza Brand To Europe With Striking D9 Minivan\n'
'2024 U.S. Electric Cars Listed From Lowest To Highest Energy '
'Consumption\n'
'This Dodge Ram Pickup Was Destroyed After Rear-Ending A Tesla '
'Cybertruck Search for:\n'
'Armored Glass Repels Tesla Cybertruck Smash-And-Grab Attempt\n'
'Toyota’s New Engine Can Suck Carbon Out Of The Air\n'
"Hyundai Confirms Its Georgia 'Metaplant' EV Factory Is Opening "
'Early\n'
'2024 U.S. Electric Cars Compared By Price Per Mile Of EPA Range\n'
'This Guy Told Us He Bought All The Cakes, Buick Wildcat Concept '
"Could Inspire 'Exceptional By Design' EVs\n"
'Hyundai Kills All N Gasoline Performance Cars In Europe\n'
'China Plug-In Car Sales Almost Doubled In January 2024\n'
'Car Buying Service\n'
'Get upfront price offers on local inventory.\n',
'origin': 'foreign',
'score': 0.6347929},
{'content': 'Electric Cars news - Today’s latest updates - CBS News CBS News '
'Miami investigative reporter Jim Defede and CBS News Texas '
'investigative reporter Brian New break down how lawmakers and '
'residents in their states view climate change amid natural '
'disasters. #### U.S. News lists its best electric and hybrid '
"vehicles for 2024 Foreign automakers dominate U.S. News' list of "
'the best new EVs and hybrids, while Tesla is shut out. #### '
'Latest CBS News Videos #### California councilwoman on '
'evacuations L.A. City Councilmember Nithya Raman told CBS News '
'Los Angeles the latest updates on the Sunset Fire burning in the '
"Hollywood Hills on Wednesday evening. CBS News Los Angeles' Joy "
'Benedict reports that some firefighters ran out of water, but '
'got help from other departments.',
'origin': 'foreign',
'score': 0.63125396},
{'content': 'Although Genesis and Hyundai plan to make some of their EVs in '
'the U.S., the biggest, most expensive electric SUV planned for '
'the lineup will be Korean-made, according to a report and plant '
'announcement.\n'
' The Audi E-Tron SUV—now the Q8 E-Tron—topped the list, with '
'data showing it retained the highest ratio of its range in '
'freezing temps.\n'
' The Lucid Gravity will help the startup automaker break into '
'the heart of the automotive market with a three-row crossover '
'SUV.\n'
' Tesla may have installed the wrong airbag for Model S and Model '
'X owners who opted to switch from the available steering yoke '
'back to the steering wheel, or vice versa.\n'
' The GM luxury brand confirmed the Optiq as the "entry point for '
'Cadillac’s EV lineup in North America," sitting below the '
'Lyriq.\n',
'origin': 'foreign',
'score': 0.586926},
{'content': 'China Plug-In Car Sales Almost Doubled In January 2024\n'
'2024 Volkswagen ID.4 Starts At $39,735, Pro Models Get More '
'Powerful\n'
'Armored Glass Repels Tesla Cybertruck Smash-And-Grab Attempt\n'
'The Apple Car Is Finally Dead, Shrouded In Mystery Until The '
'End: Report\n'
'Toyota’s New Engine Can Suck Carbon Out Of The Air\n'
"Hyundai Confirms Its Georgia 'Metaplant' EV Factory Is Opening "
'Early\n'
'2024 U.S. Electric Cars Compared By Price Per Mile Of EPA Range\n'
'One-Year-Old Kia Niro EVs Are Depreciating But Then The Story '
'Got Weird\n'
'What Trump Got Wrong About EVs During His Michigan Speech\n'
"The Polestar 3 Can't Come Soon Enough\n"
'Tesla Arson Suspect Caught On Camera: Two Model Ys Burnt\n'
'The 2025 Honda CR-V e:FCEV Is A Hydrogen Plug-In Hybrid, For '
'Real\n'
'FreeWire’s New Pro Series DC Fast Chargers Can Also Power Your '
'Business\n'
'Will Americans Buy This Tiny, Cute Electric Car?\n'
" Buick Wildcat Concept Could Inspire 'Exceptional By Design' "
'EVs\n'
'Hyundai Kills All N Gasoline Performance Cars In Europe\n'
"American Test Of $11,500 BYD Seagull: 'This Doesn't Come Across "
"Cheap'\n"
'Features\n'
'What To Do If You’ve Just Rented An Electric Car\n'
'Is A Used Mini Cooper SE The Perfect Second Car?\n'
' Until The End: Report\n'
'Reviews\n'
'The e:NY1 Shows Honda Isn’t Trying Hard Enough On EVs\n'
"The 2024 Honda Prologue Should Tide You Over Til' Dinner's "
'Ready\n'
'We Have A Tesla Cybertruck. And Hard\n'
'Reviews\n'
'The e:NY1 Shows Honda Isn’t Trying Hard Enough On EVs\n'
"The 2024 Honda Prologue Should Tide You Over Til' Dinner's "
'Ready\n'
'We Have A Tesla Cybertruck.',
'origin': 'foreign',
'score': 0.562874},
{'content': 'The company’s Cooper SE previously held the distinction of '
'having the lowest range of any EV available in the U.S. While '
'the Aceman will exceed that car’s 114 miles, it’s not expected '
'to break 300 miles. A smaller electric SUV that will bring '
'Rivian design within reach of the average car buyer, the R2 is '
'said to have a range of at least 300 miles, regardless of '
'powertrain. You can also stay up to date on the latest EV news '
'on the\xa0TrueCar Blog\xa0or on our\xa0Electric Vehicles Hub. '
'And when you’re ready to buy an electric vehicle, you can use\xa0'
'TrueCar\xa0to shop and get an up-front, personalized offer from '
'a Certified Dealer.',
'origin': 'foreign',
'score': 0.559411},
{'content': 'Best electric cars arriving in 2025 - Car News | CarsGuide Sell '
'my car Sign up / Sign in Welcome back! Sign up / Sign in New to '
'Carsguide? Sign up Welcome back! Sign in Help buy + sell Buy Buy '
'a car New What car should I buy? Sell Sell my car reviews '
'Reviews All reviewsBrowse over 9,000 car reviews FamilyFamily '
'focused reviews and advice for everything family car related. '
"Here's what to look out for and buy smart Buying guides Electric "
"news News Latest newsWhat's happening in the automotive world "
'Motor showsThe stars of the latest big events TechnologyThe '
"latest and future car tech from around the world All adviceWe're "
'here to help you with any car issues',
'origin': 'foreign',
'score': 0.5059329},
{'content': "Uncertainty over Trump's electric vehicle policies clouds 2025 "
'forecast for carmakers | AP News AP News Alerts Keep your pulse '
'on the news with breaking news alerts from The AP.The Morning '
'Wire Our flagship newsletter breaks down the biggest headlines '
'of the day.Ground Game Exclusive insights and key stories from '
'the world of politics.Beyond the Story Executive Editor Julie '
'Pace brings you behind the scenes of the AP newsroom.AP Top 25 '
'Poll Alerts Get email alerts for every college football Top 25 '
"Poll release.AP Top 25 Women's Basketball Poll Alerts Women's "
'college basketball poll alerts and updates. NEW YORK (AP) — '
'Electric vehicle demand is expected to keep rising this year, '
'but uncertainty over policy changes and tariffs is clouding the '
'forecast.',
'origin': 'foreign',
'score': 0.36466494}]
<ipython-input-41-18507b6d9b9a>:30: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.10/migration/ return processed_document.dict()
[{'content': 'Photo Galleries\n'
'Most Popular\n'
'Motor Authority Newsletter\n'
'Sign up to get the latest performance and luxury automotive '
'news, delivered to your inbox daily!\n'
' Electric Cars\n'
'The AMG version of the EQE SUV doesn’t have the fire and fury of '
'other models from Mercedes’ performance arm.\n'
' Will the jump-started VW brand really bring out a new '
'Aristocrat, or is just protecting IP?\n'
'VW is working on an electric GTI but it might not be '
'Golf-based.\n'
' The 1,234-hp Lucid Air Sapphire is the quickest car ever to '
'grace the MA Best Car To Buy competition.\n'
' The 964 RSR is a dream car for 911 fans of a certain age, and '
'Everrati is looking to capitalize with an electric tribute.\n',
'origin': 'foreign',
'score': 0.7156829},
{'content': 'Electric Cars news & latest pictures from Newsweek.com Newsweek '
'pulls back the curtain on what goes has gone into developing '
"Rivian's electric vehicle charging network. U.S. Electric "
'vehicles improved but still less reliable than gas models: '
'survey Donald Trump is reportedly planning to scrap a $7,500 '
'federal consumer tax credit for electric vehicles. Gavin Newsom '
'prepared to challenge Trump on electric vehicle tax credits '
'Gavin Newsom prepared to challenge Trump on electric vehicle tax '
'credits Newsom proposes California offer state tax rebates for '
'electric vehicle purchases should Donald Trump eliminate the '
'federal EV tax credit. Getting rid of the federal rebate could '
'devastate the electric vehicle industry, but Tesla CEO Elon Musk '
"doesn't mind. U.S. awards $3 billion for EV battery production "
'to counter China',
'origin': 'foreign',
'score': 0.6617704},
{'content': 'Read the latest electric vehicle news, recent EV reviews and EV '
'buying advice at Cars.com.',
'origin': 'foreign',
'score': 0.6453216},
{'content': 'Electric Cars news - Today’s latest updates - CBS News CBS News '
'Miami investigative reporter Jim Defede and CBS News Texas '
'investigative reporter Brian New break down how lawmakers and '
'residents in their states view climate change amid natural '
'disasters. #### U.S. News lists its best electric and hybrid '
"vehicles for 2024 Foreign automakers dominate U.S. News' list of "
'the best new EVs and hybrids, while Tesla is shut out. #### '
'Latest CBS News Videos #### California councilwoman on '
'evacuations L.A. City Councilmember Nithya Raman told CBS News '
'Los Angeles the latest updates on the Sunset Fire burning in the '
"Hollywood Hills on Wednesday evening. CBS News Los Angeles' Joy "
'Benedict reports that some firefighters ran out of water, but '
'got help from other departments.',
'origin': 'foreign',
'score': 0.63125396},
{'content': 'China Plug-In Car Sales Almost Doubled In January 2024\n'
'2024 Volkswagen ID.4 Starts At $39,735, Pro Models Get More '
'Powerful\n'
'Armored Glass Repels Tesla Cybertruck Smash-And-Grab Attempt\n'
'The Apple Car Is Finally Dead, Shrouded In Mystery Until The '
'End: Report\n'
'Toyota’s New Engine Can Suck Carbon Out Of The Air\n'
"Hyundai Confirms Its Georgia 'Metaplant' EV Factory Is Opening "
'Early\n'
'2024 U.S. Electric Cars Compared By Price Per Mile Of EPA Range\n'
'One-Year-Old Kia Niro EVs Are Depreciating But Then The Story '
'Got Weird\n'
'What Trump Got Wrong About EVs During His Michigan Speech\n'
"The Polestar 3 Can't Come Soon Enough\n"
'Tesla Arson Suspect Caught On Camera: Two Model Ys Burnt\n'
'The 2025 Honda CR-V e:FCEV Is A Hydrogen Plug-In Hybrid, For '
'Real\n'
'FreeWire’s New Pro Series DC Fast Chargers Can Also Power Your '
'Business\n'
'Will Americans Buy This Tiny, Cute Electric Car?\n'
" Buick Wildcat Concept Could Inspire 'Exceptional By Design' "
'EVs\n'
'Hyundai Kills All N Gasoline Performance Cars In Europe\n'
"American Test Of $11,500 BYD Seagull: 'This Doesn't Come Across "
"Cheap'\n"
'Features\n'
'What To Do If You’ve Just Rented An Electric Car\n'
'Is A Used Mini Cooper SE The Perfect Second Car?\n'
' Until The End: Report\n'
'Reviews\n'
'The e:NY1 Shows Honda Isn’t Trying Hard Enough On EVs\n'
"The 2024 Honda Prologue Should Tide You Over Til' Dinner's "
'Ready\n'
'We Have A Tesla Cybertruck. And Hard\n'
'Reviews\n'
'The e:NY1 Shows Honda Isn’t Trying Hard Enough On EVs\n'
"The 2024 Honda Prologue Should Tide You Over Til' Dinner's "
'Ready\n'
'We Have A Tesla Cybertruck.',
'origin': 'foreign',
'score': 0.56258565}]
<ipython-input-41-18507b6d9b9a>:30: PydanticDeprecatedSince20: The `dict` method is deprecated; use `model_dump` instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.10/migration/ return processed_document.dict()
Here is some recent news on electric cars: 1. **SK Signet Inks Deal with Francis Energy for Ultra-Fast EV Chargers:** - **Date:** July 18, 2023 - **Details:** SK Signet signed a deal with Francis Energy to supply more than 1000 ultra-fast EV chargers in the US. Francis Energy is currently the fourth-largest fast charger operator in the United States. - [Read more](https://www.econotimes.com/SK-signet-Inks-Deal-with-Francis-Energy-for-the-Supply-of-Ultra-Fast-EV-Chargers-to-the-US-1659601) 2. **YS Tech Working Closely with Chinese Car Vendors:** - **Date:** March 10, 2023 - **Details:** Automotive cooling fan supplier YS Tech is collaborating with Chinese customers and is anticipating a new Chinese government policy to boost its EV sector. - [Read more](https://www.digitimes.com/news/a20230309PD211/automotive-china-ev+green-energy-ys-tech.html) 3. **MotorTrend's New Electric Car Models:** - 2025 Dodge Charger Sixpack is reportedly fast-tracked. - New models like the 2025 Porsche Taycan and 2026 Cadillac Vistiq are highlighted, promising more excellence and sharp design in electric vehicle offerings. - Mercedes-AMG is targeting Porsche with a high-performance electric SUV. 4. **Hyundai's Electric Models and Plans:** - Although Genesis and Hyundai plan to manufacture some EVs in the U.S., their largest electric SUV will continue to be made in Korea. - Hyundai confirmed its "Metaplant" EV factory in Georgia will open earlier than planned. 5. **General Observations:** - The Audi Q8 E-Tron retains a high range in freezing temperatures. - Tesla faced issues with incorrectly installed airbags for models switching between steering wheel configurations. For more in-depth reviews and buying advice on electric vehicles, you can visit platforms like Cars.com.
[ModelRequest(parts=[SystemPromptPart(content='You get the latest news based on a user query', dynamic_ref=None, part_kind='system-prompt'), UserPromptPart(content='Get me some news on electric cars if possible', timestamp=datetime.datetime(2025, 1, 9, 18, 39, 45, 435371, tzinfo=datetime.timezone.utc), part_kind='user-prompt')], kind='request'),
, ModelResponse(parts=[ToolCallPart(tool_name='retrieve_information_from_knowledge_base', args=ArgsJson(args_json='{"user_query": "electric cars news"}'), tool_call_id='call_c10S8UWOpb2Pxn8U56W4sLvm', part_kind='tool-call'), ToolCallPart(tool_name='get_search_results_from_internet_search', args=ArgsJson(args_json='{"user_query": "electric cars news"}'), tool_call_id='call_xcF2cH3F4K9glpRLCAJo0Q44', part_kind='tool-call')], timestamp=datetime.datetime(2025, 1, 9, 18, 39, 45, tzinfo=datetime.timezone.utc), kind='response'),
, ModelRequest(parts=[ToolReturnPart(tool_name='retrieve_information_from_knowledge_base', content='[{\'companyName\': \'01Synergy\', \'companyUrl\': \'https://hackernoon.com/company/01synergy\', \'published_at\': \'2023-07-18 08:31:00\', \'title\': \'SK signet Inks Deal with Francis Energy for the Supply of Ultra-Fast EV Chargers to the US\', \'description\': \'SK Signet revealed it signed a deal with Francis Energy for an order of more than 1000 EV chargers. The latter is currently the fourth-largest fast charger operator in the United States and it has agreed to a\', \'url\': \'https://www.econotimes.com/SK-signet-Inks-Deal-with-Francis-Energy-for-the-Supply-of-Ultra-Fast-EV-Chargers-to-the-US-1659601\', \'score\': 0.7703076601028442}, {\'companyName\': \'01Synergy\', \'companyUrl\': \'https://hackernoon.com/company/01synergy\', \'published_at\': \'2023-03-10 02:28:00\', \'title\': \'YS Tech working closely with China car vendors\', \'description\': "Automotive cooling fan supplier Yen Sun Technology (YS Tech) said it will work closely with Chinese customers and is anticipating a new Chinese government policy to boost the country\'s EV sector.", \'url\': \'https://www.digitimes.com/news/a20230309PD211/automotive-china-ev+green-energy-ys-tech.html\', \'score\': 0.7642202377319336}, {\'companyName\': \'01Synergy\', \'companyUrl\': \'https://hackernoon.com/company/01synergy\', \'published_at\': \'2023-03-10 02:28:00\', \'title\': \'YS Tech working closely with China car vendors\', \'description\': "Automotive cooling fan supplier Yen Sun Technology (YS Tech) said it will work closely with Chinese customers and is anticipating a new Chinese government policy to boost the country\'s EV sector.", \'url\': \'https://www.digitimes.com/news/a20230309PD211/automotive-china-ev+green-energy-ys-tech.html\', \'score\': 0.7642202377319336}, {\'companyName\': \'01Synergy\', \'companyUrl\': \'https://hackernoon.com/company/01synergy\', \'published_at\': \'2023-03-10 02:28:00\', \'title\': \'YS Tech working closely with China car vendors\', \'description\': "Automotive cooling fan supplier Yen Sun Technology (YS Tech) said it will work closely with Chinese customers and is anticipating a new Chinese government policy to boost the country\'s EV sector.", \'url\': \'https://www.digitimes.com/news/a20230309PD211/automotive-china-ev+green-energy-ys-tech.html?chid=13\', \'score\': 0.7642202377319336}, {\'companyName\': \'10Clouds\', \'companyUrl\': \'https://hackernoon.com/company/10clouds\', \'published_at\': \'2023-01-30 14:08:00\', \'title\': \'Investing in Cleaner Technology: Lesser-Known Areas of Innovation to Watch\', \'description\': \'That said January has seen two powerful news events that may have slipped under your radar but that have the potential to have enormous impact on the efforts towards cleaner energy. Here we are going to look at cleaner energy investment opportunities that can help bridge the gap between where the science and our needs are today versus where we want to be in the future.\', \'url\': \'https://www.nasdaq.com/articles/investing-in-cleaner-technology%3A-lesser-known-areas-of-innovation-to-watch\', \'score\': 0.7604036331176758}]', tool_call_id='call_c10S8UWOpb2Pxn8U56W4sLvm', timestamp=datetime.datetime(2025, 1, 9, 18, 39, 47, 477184, tzinfo=datetime.timezone.utc), part_kind='tool-return'), ToolReturnPart(tool_name='get_search_results_from_internet_search', content=[{'score': 0.8463680744171143, 'origin': 'local'}, {'score': 0.8341740965843201, 'origin': 'local'}, {'score': 0.8332723379135132, 'origin': 'local'}, {'score': 0.8189547657966614, 'origin': 'local'}, {'score': 0.8049435615539551, 'origin': 'local'}, {'content': 'MotorTrend | News 2025 Dodge Charger Sixpack Gas Muscle Car is Reportedly Getting Fast-Tracked ---------------------------------------------------------------------------- Andrew Beckford | Nov 12, 2024 MotorTrend | First Look 2025 Porsche Taycan First Look: More Excellence ----------------------------------------------- Frank Markus | Nov 12, 2024 MotorTrend | First Look 2026 Cadillac Vistiq First Look: Sharp All-Electric 3-Row Family SUV -------------------------------------------------------------------- Alex Leanse | Nov 12, 2024 MotorTrend | News Next-Gen Chevrolet Bolt EV Kills Off a Cadillac SUV --------------------------------------------------- Justin Westbrook | Nov 11, 2024 MotorTrend | Future Cars Mercedes-AMG Going After Porsche With High-Performance Electric SUV ------------------------------------------------------------------- Justin Westbrook | Nov 7, 2024', 'score': 0.82082915, 'origin': 'foreign'}, {'content': 'Photo Galleries\nMost Popular\nMotor Authority Newsletter\nSign up to get the latest performance and luxury automotive news, delivered to your inbox daily!\n Electric Cars\nThe AMG version of the EQE SUV doesn’t have the fire and fury of other models from Mercedes’ performance arm.\n Will the jump-started VW brand really bring out a new Aristocrat, or is just protecting IP?\nVW is working on an electric GTI but it might not be Golf-based.\n The 1,234-hp Lucid Air Sapphire is the quickest car ever to grace the MA Best Car To Buy competition.\n The 964 RSR is a dream car for 911 fans of a certain age, and Everrati is looking to capitalize with an electric tribute.\n', 'score': 0.81665546, 'origin': 'foreign'}, {'content': 'Although Genesis and Hyundai plan to make some of their EVs in the U.S., the biggest, most expensive electric SUV planned for the lineup will be Korean-made, according to a report and plant announcement.\n The Audi E-Tron SUV—now the Q8 E-Tron—topped the list, with data showing it retained the highest ratio of its range in freezing temps.\n The Lucid Gravity will help the startup automaker break into the heart of the automotive market with a three-row crossover SUV.\n Tesla may have installed the wrong airbag for Model S and Model X owners who opted to switch from the available steering yoke back to the steering wheel, or vice versa.\n The GM luxury brand confirmed the Optiq as the "entry point for Cadillac’s EV lineup in North America," sitting below the Lyriq.\n', 'score': 0.769306, 'origin': 'foreign'}, {'content': "And Hard\nThe 2025 Honda CR-V e:FCEV Is A Hydrogen Plug-In Hybrid, For Real\nEV News\nFilter by:\nWhy Is Motorcycle Racing Afraid Of This Electric Bike?\nChinese Cars Would Get 125% Price Increase Under New Senate Bill\nWatch Tesla Cybertruck Owner Shoot Bullets At His Truck With Submachine Gun, Shotgun\n'Mind-Blowing' Tesla Roadster Final Form To Debut But Then The Story Got Weird\nWhat Trump Got Wrong About EVs During His Michigan Speech\nThe Polestar 3 Can't Come Soon Enough\nTesla Arson Suspect Caught On Camera: Two Model Ys Burnt\nFreeWire’s New Pro Series DC Fast Chargers Can Also Power Your Business\nWill Americans Buy This Tiny, Cute Electric Car?\n It May Work\nWatch Ford's 1,400-HP SuperVan Blast Its Way To Several Lap Records At Bathurst\nElectrification Leads To All-Wheel-Drive Dominance\nBYD Brings Denza Brand To Europe With Striking D9 Minivan\n2024 U.S. Electric Cars Listed From Lowest To Highest Energy Consumption\nThis Dodge Ram Pickup Was Destroyed After Rear-Ending A Tesla Cybertruck Search for:\nArmored Glass Repels Tesla Cybertruck Smash-And-Grab Attempt\nToyota’s New Engine Can Suck Carbon Out Of The Air\nHyundai Confirms Its Georgia 'Metaplant' EV Factory Is Opening Early\n2024 U.S. Electric Cars Compared By Price Per Mile Of EPA Range\nThis Guy Told Us He Bought All The Cakes, Buick Wildcat Concept Could Inspire 'Exceptional By Design' EVs\nHyundai Kills All N Gasoline Performance Cars In Europe\nChina Plug-In Car Sales Almost Doubled In January 2024\nCar Buying Service\nGet upfront price offers on local inventory.\n", 'score': 0.76826453, 'origin': 'foreign'}, {'content': 'Read the latest electric vehicle news, recent EV reviews and EV buying advice at Cars.com.', 'score': 0.7646988, 'origin': 'foreign'}], tool_call_id='call_xcF2cH3F4K9glpRLCAJo0Q44', timestamp=datetime.datetime(2025, 1, 9, 18, 39, 50, 864331, tzinfo=datetime.timezone.utc), part_kind='tool-return')], kind='request'),
, ModelResponse(parts=[TextPart(content='Here is some recent news on electric cars:\n\n1. **SK Signet Inks Deal with Francis Energy for Ultra-Fast EV Chargers:**\n - **Date:** July 18, 2023\n - **Details:** SK Signet signed a deal with Francis Energy to supply more than 1000 ultra-fast EV chargers in the US. Francis Energy is currently the fourth-largest fast charger operator in the United States.\n - [Read more](https://www.econotimes.com/SK-signet-Inks-Deal-with-Francis-Energy-for-the-Supply-of-Ultra-Fast-EV-Chargers-to-the-US-1659601)\n\n2. **YS Tech Working Closely with Chinese Car Vendors:**\n - **Date:** March 10, 2023\n - **Details:** Automotive cooling fan supplier YS Tech is collaborating with Chinese customers and is anticipating a new Chinese government policy to boost its EV sector.\n - [Read more](https://www.digitimes.com/news/a20230309PD211/automotive-china-ev+green-energy-ys-tech.html)\n\n3. **MotorTrend\'s New Electric Car Models:**\n - 2025 Dodge Charger Sixpack is reportedly fast-tracked.\n - New models like the 2025 Porsche Taycan and 2026 Cadillac Vistiq are highlighted, promising more excellence and sharp design in electric vehicle offerings.\n - Mercedes-AMG is targeting Porsche with a high-performance electric SUV.\n\n4. **Hyundai\'s Electric Models and Plans:**\n - Although Genesis and Hyundai plan to manufacture some EVs in the U.S., their largest electric SUV will continue to be made in Korea.\n - Hyundai confirmed its "Metaplant" EV factory in Georgia will open earlier than planned.\n\n5. **General Observations:**\n - The Audi Q8 E-Tron retains a high range in freezing temperatures.\n - Tesla faced issues with incorrectly installed airbags for models switching between steering wheel configurations.\n\nFor more in-depth reviews and buying advice on electric vehicles, you can visit platforms like Cars.com.', part_kind='text')], timestamp=datetime.datetime(2025, 1, 9, 18, 39, 50, tzinfo=datetime.timezone.utc), kind='response')] 