OpenAI Web Search API
The OpenAI Web Search API is a convenient way of accessing the web with a set of parameters to filter on…
Language Models have become the backbone of Agentic Applications and AI Agents.
The challenge is that Language Models have a cut-off date in terms of data recency, the data which was included in their t training.
In the recent past web search, web scraping APIs needed to be used, or web browsing tools. Or specific API’s needed to be integrated for news, weather etc.
OpenAI recently launched a web search API…
The advantage of using the OpenAI Web Search API is that it is a confined and easy to manage API with different filters which can be used.
So users can define criteria and get web based results back with references, where in the recent past specific tools had to be made use of for web access.
So this API comes with a high level of convenience and implementation easy…but…there are considerations…
The ability to perform domain filtering is convenient to create a search functionality for a website…
Filters include web domains, location, city, country, region, time zone and context size…

Considerations
Although there is a fairly granular level of filtering and settings available, the orchestration performed under the hood, or behind the API is currently a back box.
OpenAI did recently lift the veil on the deep research API orchestration and ChatGPT orchestration behind the UI…which was insightful.
The API uses a dedicated model, gpt-4o-search-preview
, and when you enable the web search tool, the model will attempt to use it, regardless of whether the question could be answered confidently without external data.
Hence there seems to be no intelligent orchestration behind the API…hence users will have to implement an orchestration layer in their framework to distinguish when a user query needs to go to the web or not.
So the API does not dynamically skip the web search just because the model “knows” the answer.
Most probably the search API uses Bing, and this is also something to keep in mind if you as a developer wants to make use of a specific search engine.
I would argue this API is well suited for organisations which are deep into OpenAI tech and implementations, or for experimenting. But for an enterprise implementation I would argue that a more decomposed and granular approach will work better.
One might want to make use of disambiguation and ask the user if the AI Agent or UI can search the web for an answer, in instances where no other data is available…
Below is a diagram I came up with, on how the API works…based on what is known.
Most Basic Example
Currently, you need to use one of these models to use web search in Chat Completions:
gpt-4o-search-preview
gpt-4o-mini-search-preview
Below is the most basic example of a Python web search application…you can copy and paste this code into a Colab notebook.
from openai import OpenAI
from google.colab import userdata
import os
# Attempt to get API key from environment variable first, then from Colab secrets
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
try:
api_key = userdata.get('OPENAI_API_KEY')
except userdata.SecretNotFoundError:
print("OPENAI_API_KEY not found in Colab secrets. Please add it.")
api_key = None
if api_key:
client = OpenAI(api_key=api_key)
completion = client.chat.completions.create(
model="gpt-4o-search-preview",
web_search_options={},
messages=[
{
"role": "user",
"content": "What is the current weather in SF?",
}
],
)
print(completion.choices[0].message.content)
else:
print("OpenAI API key is not set. Please set it in Colab secrets or as an environment variable.")
And the response…
As of 6:00 AM on Tuesday, September 2, 2025, in San Francisco, CA, the weather is mostly clear with a temperature of 62°F (16°C).
## Weather for San Francisco, CA:
Current Conditions: Mostly clear, 62°F (16°C)
Daily Forecast:
* Monday, September 1: Low: 59°F (15°C), High: 74°F (23°C), Description: Mostly sunny and pleasant
* Tuesday, September 2: Low: 61°F (16°C), High: 73°F (23°C), Description: Low clouds followed by sunshine
* Wednesday, September 3: Low: 60°F (16°C), High: 71°F (22°C), Description: Clouds giving way to sun
* Thursday, September 4: Low: 60°F (15°C), High: 67°F (20°C), Description: Clouds giving way to sun
* Friday, September 5: Low: 59°F (15°C), High: 71°F (22°C), Description: Clouds giving way to sun
* Saturday, September 6: Low: 60°F (16°C), High: 68°F (20°C), Description: Mostly sunny
* Sunday, September 7: Low: 61°F (16°C), High: 70°F (21°C), Description: Sun and areas of low clouds and beautiful
Domain Filtering
Domain filtering in web search allows you to restrict results to a specific group of domains.
Using the filters parameter, you can create an allow-list of up to 20 domains.
When specifying domain URLs, exclude the HTTP or HTTPS prefix, e.g., use openai.com instead of
https://openai.com/
.
This method also includes subdomains in the search.
Domain filtering is exclusively available in the Responses API with the web_search tool.
Basic working code example:
from openai import OpenAI
from google.colab import userdata
import os
# Attempt to get API key from environment variable first, then from Colab secrets
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
try:
api_key = userdata.get('OPENAI_API_KEY')
except userdata.SecretNotFoundError:
print("OPENAI_API_KEY not found in Colab secrets. Please add it.")
api_key = None
if api_key:
client = OpenAI(api_key=api_key)
response = client.responses.create(
model="gpt-5",
reasoning={"effort": "low"},
tools=[
{
"type": "web_search",
"filters": {
"allowed_domains": [
"pubmed.ncbi.nlm.nih.gov",
"clinicaltrials.gov",
"www.who.int",
"www.cdc.gov",
"www.fda.gov"
]
}
}
],
tool_choice="auto",
include=["web_search_call.action.sources"],
input="Please perform a web search on how semaglutide is used in the treatment of diabetes."
)
print(response.output_text)
else:
print("OpenAI API key is not set. Please set it in Colab secrets or as an environment variable.")
And the output:
Here’s what authoritative sources (FDA, CDC, WHO, PubMed) say about how semaglutide is used to treat diabetes:
What it is and indications
- Semaglutide is a GLP-1 receptor agonist used to improve glycemic control in adults with type 2 diabetes, as an adjunct to diet and exercise. FDA‑approved diabetes products are Ozempic (weekly injection) and Rybelsus (oral tablets). Ozempic also reduces the risk of major adverse cardiovascular events in adults with type 2 diabetes and established cardiovascular disease. ([fda.gov](https://www.fda.gov/drugs/drug-approvals-and-databases/drug-trial-snapshot-Ozempic?utm_source=openai))
Formulations and how it’s taken
- Injection: Ozempic is given once weekly subcutaneously (abdomen, thigh, or upper arm). It may be used alone or with other diabetes medicines (for example, metformin, sulfonylureas, thiazolidinediones, or insulin; if used with insulin, inject separately). ([fda.gov](https://www.fda.gov/drugs/drug-approvals-and-databases/drug-trial-snapshot-Ozempic?utm_source=openai))
- Oral: Rybelsus is the first FDA‑approved oral GLP‑1; it’s taken once daily. In trials supporting approval, meaningful A1c reductions occurred with 7 mg and 14 mg doses. The FDA announcement notes boxed warnings and that Rybelsus is not recommended as the first choice of medicine for treating diabetes; it is not for type 1 diabetes or DKA. ([fda.gov](https://www.fda.gov/news-events/press-announcements/fda-approves-first-oral-glp-1-treatment-type-2-diabetes?sfns=mo&utm_source=openai))
Effectiveness (A1c, weight, and CV outcomes)
- Across pivotal SUSTAIN trials, semaglutide lowered A1c more than comparators such as sitagliptin, insulin glargine, and canagliflozin, and produced weight loss; GI adverse effects were the most common. ([pubmed.ncbi.nlm.nih.gov](https://pubmed.ncbi.nlm.nih.gov/28385659/?utm_source=openai))
- Higher‑dose semaglutide 2.0 mg weekly provided additional A1c reduction versus 1.0 mg in SUSTAIN FORTE. ([pubmed.ncbi.nlm.nih.gov](https://pubmed.ncbi.nlm.nih.gov/34293304/?utm_source=openai))
- In SUSTAIN‑6 (patients with T2D at high CV risk), semaglutide reduced the composite of CV death, nonfatal MI, or nonfatal stroke versus placebo. ([pubmed.ncbi.nlm.nih.gov](https://pubmed.ncbi.nlm.nih.gov/27633186/?utm_source=openai))
Safety, warnings, and precautions
- Common adverse effects: nausea, vomiting, diarrhea, abdominal pain, constipation. Serious risks include pancreatitis; worsening of diabetic retinopathy has been observed; hypoglycemia risk can increase when combined with insulin or sulfonylureas. ([fda.gov](https://www.fda.gov/drugs/drug-approvals-and-databases/drug-trial-snapshot-Ozempic?utm_source=openai))
- Boxed warning: risk of thyroid C‑cell tumors; do not use in patients with personal/family history of medullary thyroid carcinoma or with MEN2. ([fda.gov](https://www.fda.gov/news-events/press-announcements/fda-approves-first-oral-glp-1-treatment-type-2-diabetes?sfns=mo&utm_source=openai))
- Not indicated for type 1 diabetes or diabetic ketoacidosis. ([fda.gov](https://www.fda.gov/news-events/press-announcements/fda-approves-first-oral-glp-1-treatment-type-2-diabetes?sfns=mo&utm_source=openai))
- FDA and WHO have warned about counterfeit/falsified GLP‑1 products; patients should obtain medications only via valid prescriptions from licensed pharmacies. ([fda.gov](https://www.fda.gov/drugs/drug-safety-and-availability/fda-warns-consumers-not-use-counterfeit-ozempic-semaglutide-found-us-drug-supply-chain?utm_source=openai), [who.int](https://www.who.int/news/item/29-01-2024-shortages-impacting-access-to-glucagon-like-peptide-1-receptor-agonist-products--increasing-the-potential-for-falsified-versions?utm_source=openai))
How it fits into current practice
- CDC summarizes that newer agents like GLP‑1 RAs (including semaglutide) are recommended in recent ADA/EASD guidance for many adults with type 2 diabetes, particularly those with ASCVD, heart failure, or chronic kidney disease, reflecting benefits beyond glucose lowering. ([cdc.gov](https://www.cdc.gov/diabetes/data-research/research/new-diabetes-medicines.html?utm_source=openai))
- Use of GLP‑1 injectables among U.S. adults with diagnosed diabetes increased markedly by 2024. ([cdc.gov](https://www.cdc.gov/nchs/products/databriefs/db537.htm?utm_source=openai))
If you want, I can pull the current FDA Prescribing Information PDFs for Ozempic and Rybelsus next and extract the exact dosing/titration schedules.
Location Filtering
To filter search results by location, you can include an approximate user location using country, city, region, and/or timezone.
City and region are free-text strings, such as Minneapolis and Minnesota, respectively.
Country is a two-letter ISO country code, such as US.
Timezone is an IANA timezone, such as America/Chicago.
Basic code example:
from openai import OpenAI
from google.colab import userdata
import os
# Attempt to get API key from environment variable first, then from Colab secrets
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
try:
api_key = userdata.get('OPENAI_API_KEY')
except userdata.SecretNotFoundError:
print("OPENAI_API_KEY not found in Colab secrets. Please add it.")
api_key = None
if api_key:
client = OpenAI(api_key=api_key)
completion = client.chat.completions.create(
model="gpt-4o-search-preview",
web_search_options={
"user_location": {
"type": "approximate",
"approximate": {
"country": "GB",
"city": "London",
"region": "London",
}
},
},
messages=[{
"role": "user",
"content": "What are the best restaurants around Granary Square?",
}],
)
print(completion.choices[0].message.content)
else:
print("OpenAI API key is not set. Please set it in Colab secrets or as an environment variable.")
And the output:
Granary Square in King's Cross is a vibrant area offering a diverse selection of dining options. Here are some notable restaurants you might consider:
**[Granary Square Brasserie](https://granarysquarebrasserie.com/?utm_medium=Organic&utm_source=openai)**
**Closed · $$$ · 4.2 (2857 reviews)**
_1 Granary Square, London N1C 4AA, United Kingdom_
An all-day dining spot offering classic British and European dishes in a plush, jewel-coloured setting. Ideal for leisurely brunches or special celebrations.
**[Coal Office Restaurant](http://coaloffice.com/?utm_source=openai)**
**Closed · $$ · 4.6 (2176 reviews)**
_2 Bagley Walk, London N1C 4PQ, United Kingdom_
Serving Mediterranean and Middle Eastern cuisine with a concept of sharing food between a group of people, offering an alternative Sunday lunch with sharing starters followed by a choice of mains.
**[Dishoom Covent Garden](https://www.dishoom.com/covent-garden/?utm_medium=organic&utm_campaign=Yext&utm_content=D1-CoventGarden&y_source=1_MjMwNDkyMDMtNzE1LWxvY2F0aW9uLndlYnNpdGU%3D&utm_source=openai)**
**Closed · $$ · 4.7 (27318 reviews)**
_12 Upper St Martin's Ln, London, WC2H 9FB, United Kingdom_
A popular Indian restaurant serving authentic Bombay-style cuisine, including breakfast bacon naans that have earned cult status among locals.
**[hicce restaurant & mkt](https://www.hicce.co.uk/?utm_source=openai)**
**Closed · 4.2 (806 reviews)**
_102 Stable St, London N1C 4DQ, United Kingdom_
Offers European contemporary cuisine with a focus on wood-fired cooking, providing a unique dining experience in a stylish setting.
Each of these establishments offers a unique dining experience, contributing to the dynamic culinary scene around Granary Square.
Search Context Size
The search_context_size
parameter controls the amount of web context retrieved for a response.
The tokens are used solely for the tool’s response and do not affect the main model’s context window, as they are discarded afterward.
Cost
Tokens may be free for some models but charged at text token rates for others. Refer to pricing for details.
Quality
Larger context sizes yield richer information, improving answer quality.
Speed
Larger context sizes process more tokens, resulting in slower responses.
Options
High: Provides the most detailed context but slowest response.
Medium (default): Balances context detail and response speed.
Low: Minimises context for the fastest response, potentially reducing answer quality.
Again, a most basic code example:
from openai import OpenAI
from google.colab import userdata
import os
# Attempt to get API key from environment variable first, then from Colab secrets
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
try:
api_key = userdata.get('OPENAI_API_KEY')
except userdata.SecretNotFoundError:
print("OPENAI_API_KEY not found in Colab secrets. Please add it.")
api_key = None
if api_key:
client = OpenAI(api_key=api_key)
completion = client.chat.completions.create(
model="gpt-4o-search-preview",
web_search_options={
"search_context_size": "low",
},
messages=[{
"role": "user",
"content": "What movie won best picture in 2025?",
}],
)
print(completion.choices[0].message.content)
else:
print("OpenAI API key is not set. Please set it in Colab secrets or as an environment variable.")
And the output:
At the 97th Academy Awards held on March 2, 2025, "Anora" won Best Picture. Directed by Sean Baker, the film is a Brooklyn-set comedy-drama about an exotic dancer who marries the son of a Russian oligarch. "Anora" received five Oscars in total, including Best Director, Best Actress for Mikey Madison, Best Editing, and Best Original Screenplay. ([apnews.com](https://apnews.com/article/796ad6e41d869cc793db1488f5a75f06?utm_source=openai))
Sean Baker made history by becoming the first person to win four Oscars for the same film, matching Walt Disney's record for the most Academy Awards won by a person in one year. ([cnbc.com](https://www.cnbc.com/amp/2025/03/02/oscar-awards-live-updates-complete-list-of-winners.html?utm_source=openai))
Other notable winners at the ceremony included Adrien Brody, who won Best Actor for his role in "The Brutalist," and Zoe Saldaña, who won Best Supporting Actress for "Emilia Pérez." ([npr.org](https://www.npr.org/2025/03/02/nx-s1-5307165/oscars-2025-complete-winners-list?utm_source=openai))
## 'Anora' Triumphs at 97th Academy Awards:
- [The Latest: 'Anora' wins best picture at the 97th Academy Awards](https://apnews.com/article/796ad6e41d869cc793db1488f5a75f06?utm_source=openai)
- ['Anora' triumphs with 5 Oscar wins including Best Picture](https://www.ft.com/content/5d75ed67-889f-49d6-b961-b3d9a4ad9169?utm_source=openai)
- [Indie movies win big at 2025 Oscars](https://www.axios.com/2025/03/03/oscars-academy-awards-anora-independent-films?utm_source=openai)
Chief Evangelist @ Kore.ai | I’m passionate about exploring the intersection of AI and language. Language Models, AI Agents, Agentic Apps, Dev Frameworks & Data-Driven Tools shaping tomorrow.
More Resources:
https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat
https://openai.com/index/introducing-chatgpt-search/
COBUS GREYLING
Where AI Meets Language | Language Models, AI Agents, Agentic Applications, Development Frameworks & Data-Centric…www.cobusgreyling.com
OpenAI API Deep Research
With the introduction of the OpenAI API for Deep Research, OpenAI also lifted the veil on the internal workings of…cobusgreyling.medium.com
OpenAI Deep Research AI Agent Architecture
Recently OpenAI shows their ideal scenario for creating a Deep Research AI Agent…cobusgreyling.medium.com