داشبورد توسعه‌دهنده
پرسش از هوش مصنوعی
پرسش از هوش مصنوعی

استفاده از قابلیت‌های جستجوی وب در مدل‌های زبانی بزرگ (LLM)

مقدمه

مدل‌های زبانی بزرگ (LLM) که به قابلیت جستجوی وب مجهز شده‌اند، توانایی استدلال پیشرفته خود را با اطلاعات لحظه‌ای و به‌روز اینترنت ترکیب می‌کنند. این راهنما چگونگی بهره‌برداری از این مدل‌ها را از طریق API یکپارچه AvalAI شرح می‌دهد. با استفاده از این قابلیت، می‌توانید برنامه‌های خود را با جدیدترین اطلاعات، پاسخ‌های مبتنی بر واقعیت و منابع معتبر و قابل استناد، غنی‌تر سازید.

ویژگی‌های کلیدی

  • بازیابی آنی اطلاعات: دسترسی به اطلاعات روزآمد، فراتر از داده‌های آموزشی مدل.
  • ارجاع به منابع (Citation): پاسخ‌ها به همراه لینک به منابع جهت بررسی صحت اطلاعات ارائه می‌شوند.
  • اجرای خودکار جستجو: مدل‌ها هوشمندانه و بر اساس نیاز پرسش، زمان لازم برای جستجو در وب را تشخیص می‌دهند.
  • رویکردهای متنوع جستجو: امکان انتخاب بین مدل‌هایی با قابلیت جستجوی داخلی یا مدل‌هایی که از طریق ابزارها (Tools) جستجو می‌کنند.
  • یکپارچه‌سازی آسان با API: استفاده از همان اندپوینت‌های آشنای API با کمترین تغییرات در پیکربندی.

مهم

این متفاوت از جستجوی وب سیستمی است که یک API جستجوی وب مستقل است که نتایج جستجوی خام را برای استفاده برنامه‌نویسی برمی‌گرداند، در حالی که جستجوی وب در chat completions پاسخ‌های هوش مصنوعی را با داده‌های وب بلادرنگ تقویت می‌کند.

مدل‌های موجود

این مدل‌ها قابلیت جستجوی وب را به صورت ذاتی در خود دارند:

  • OpenAI:
    • gpt-4o-search-preview: مدلی جامع با قابلیت‌های جستجوی یکپارچه.
    • gpt-4o-mini-search-preview: مدلی بهینه‌تر با قابلیت‌های جستجوی یکپارچه.

این مدل‌ها با استفاده از پیکربندی ابزارها قادر به انجام جستجو در وب هستند:

  • OpenAI:

    • gpt-5.5: قابلیت جستجوی وب از طریق پارامتر tools.
    • gpt-5.4: قابلیت جستجوی وب از طریق پارامتر tools.
    • gpt-5.4-chat: قابلیت جستجوی وب از طریق پارامتر tools.
  • Google:

    • gemini-3.5-flash: برای جستجو از پارامتر tools استفاده می‌کند.
    • gemini-3.1-pro-preview: برای جستجو از پارامتر tools استفاده می‌کند.
    • gemini-3.1-flash-lite: برای جستجو از پارامتر tools استفاده می‌کند.
    • gemini-2.5-pro: برای جستجو از پارامتر tools استفاده می‌کند.
    • gemini-2.5-flash: برای جستجو از پارامتر tools استفاده می‌کند.
  • Alibaba:

    • qwen3.7-max: از پارامتر enable_search با استراتژی agent استفاده می‌کند.
    • qwen3.7-plus: از پارامتر enable_search با استراتژی agent استفاده می‌کند.
    • qwen3.6-flash: از پارامتر enable_search با استراتژی agent استفاده می‌کند.

نحوه استفاده مقدماتی

جستجوی داخلی با مدل‌های OpenAI

مدل‌های دارای قابلیت جستجوی داخلی، بدون نیاز به پیکربندی خاص، به طور خودکار در صورت لزوم جستجو در وب را انجام می‌دهند:

bash
curl https://api.avalai.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-4o-search-preview",
 "messages": [{
 "role": "user",
 "content": "what'"'"'s the news today?"
 }],
 "response_format": {
 "type": "text"
 },
 "store": false
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="gpt-4o-search-preview",
    messages=[{"role": "user", "content": "what's the news today?"}],
    response_format={"type": "text"},
    store=False,
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-4o-search-preview",
  messages: [
    {
      role: "user",
      content: "what's the news today?",
    },
  ],
  response_format: {
    type: "text",
  },
  store: false,
});

// چاپ پاسخ
console.log(response.choices[0].message.content);
go
package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gpt-4o-search-preview",
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "what's the news today?",
				},
			},
			ResponseFormat: &openai.ChatCompletionResponseFormat{
				Type: openai.ChatCompletionResponseFormatTypeText,
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}

	// چاپ پاسخ
	fmt.Println(resp.Choices[0].Message.Content)
}
php
<?php

require 'vendor/autoload.php';

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

$completion = $client->chat()->create([
 'model' => 'gpt-4o-search-preview',
 'messages' => [
 [
 'role' => 'user',
 'content' => 'what\'s the news today?'
 ]
 ],
 'response_format' => [
 'type' => 'text'
 ],
 'store' => false
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;

جستجو با مدل‌های OpenAI از طریق ابزار

مدل‌های استاندارد OpenAI می‌توانند با استفاده از پارامتر tools، جستجو در وب را انجام دهند:

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-5.5",
 "tools": [{"type": "web_search"}],
 "input": "What was a positive news story from today?"
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.responses.create(
    model="gpt-5.5",
    tools=[{"type": "web_search"}],
    input="What was a positive news story from today?",
)

# چاپ متن خروجی
print(response.output_text)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-5.5",
  tools: [{ type: "web_search" }],
  input: "What was a positive news story from today?",
});

// چاپ متن خروجی
console.log(response.output_text);
go
package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateResponse(
		context.Background(),
		openai.ResponseRequest{
			Model: "gpt-5.5",
			Tools: []openai.Tool{
				{
					Type: "web_search",
				},
			},
			Input: "What was a positive news story from today?",
		},
	)

	if err != nil {
		fmt.Printf("Response error: %v\n", err)
		return
	}

	// چاپ متن خروجی
	fmt.Println(resp.OutputText)
}
php
<?php

require 'vendor/autoload.php';

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

$response = $client->responses()->create([
 'model' => 'gpt-5.5',
 'tools' => [['type' => 'web_search']],
 'input' => 'What was a positive news story from today?'
]);

// چاپ متن خروجی
echo $response->output_text;

جستجو با مدل‌های Gemini

مدل‌های Gemini برای فعال‌سازی قابلیت جستجوی وب، از پارامتر tools استفاده می‌کنند:

bash
curl -i "https://api.avalai.ir/v1/chat/completions" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
 "model": "gemini-2.5-flash",
 "messages": [{"role": "user", "content": "whats the news for today"}],
 "tools": [
 {
 "googleSearch": {}
 }
 ]
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="gemini-2.5-flash",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "whats the news?"},
    ],
    tools=[{"googleSearch": {}}],
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gemini-2.5-flash",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "whats the news?" },
  ],
  tools: [{ googleSearch: {} }],
});

// چاپ پاسخ
console.log(response.choices[0].message.content);
go
package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gemini-2.5-flash",
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleSystem,
					Content: "You are a helpful assistant.",
				},
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "whats the news?",
				},
			},
			Tools: []openai.Tool{
				{
					GoogleSearch: &openai.GoogleSearchTool{},
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();
	// چاپ پاسخ
	fmt.Println(resp.Choices[0].Message.Content)
}
php
<?php

require 'vendor/autoload.php';

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

$completion = $client->chat()->create([
 'model' => 'gemini-2.5-flash',
 'messages' => [
 [
 'role' => 'system',
 'content' => 'You are a helpful assistant.'
 ],
 [
 'role' => 'user',
 'content' => 'whats the news?'
 ]
 ],
 'tools' => [
 ['googleSearch' => new stdClass()]
 ]
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;
نسخه معادل Responses API مدل این نسخه روی `gpt-5.5` تنظیم شده، چون `gemini-2.5-flash` ممکن است در داده‌های فعلی AvalAI برای `/v1/responses` فعال نباشد.

وقتی مدل انتخابی از /v1/responses پشتیبانی می‌کند، این نسخه را کنار مثال Chat Completions استفاده کنید. messages به input منتقل می‌شود و متن نهایی از response.output_text خوانده می‌شود.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

tools = [
    {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"],
            "additionalProperties": False,
        },
    }
]

response = client.responses.create(
    model="gpt-5.5",
    input="whats the news?",
    tools=tools,
)

for item in response.output:
    if item.type == "function_call":
        print(item.name, item.arguments)
print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const tools = [
  {
    type: "function",
    name: "get_current_weather",
    description: "Get the current weather in a given location.",
    parameters: {
      type: "object",
      properties: { location: { type: "string" } },
      required: ["location"],
      additionalProperties: false,
    },
  },
];

const response = await client.responses.create({
  model: "gpt-5.5",
  input: "whats the news?",
  tools,
});

for (const item of response.output) {
  if (item.type === "function_call") {
    console.log(item.name, item.arguments);
  }
}
console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.5",
    "input": "whats the news?",
    "tools": [
      {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string"
            }
          },
          "required": [
            "location"
          ],
          "additionalProperties": false
        }
      }
    ]
  }'
  • messagesinput
  • پیام سیستمی → instructions یا آیتم developer
  • choices[0].message.contentresponse.output_text
  • برای ابزارها و خروجی‌های چندوجهی، response.output را بر اساس type بررسی کنید.

API بومی Gemini (v1beta)

علاوه بر endpoint سازگار با OpenAI که در بالا نشان داده شد، می‌توانید از API بومی Gemini گوگل (v1beta) برای ویژگی‌های پیشرفته‌تر پایه‌گذاری استفاده کنید. این رویکرد دسترسی به متادیتای پایه‌گذاری دقیق شامل استنادات، پرس‌وجوهای جستجو و اطلاعات منبع را فراهم می‌کند.

استفاده با cURL

bash
curl "https://api.avalai.ir/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $AVALAI_API_KEY" \
  -H "Content-Type: application/json" \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {"text": "آخرین پیشرفت‌ها در محاسبات کوانتومی چیست؟"}
        ]
      }
    ],
    "tools": [
      {
        "google_search": {}
      }
    ]
  }'

استفاده با SDK Google GenAI (Python)

python
from google import genai
from google.genai import types

client = genai.Client(
    api_key="your-avalai-api-key",
    http_options={"api_version": "v1beta", "base_url": "https://api.avalai.ir"},
)

response = client.models.generate_content(
    model="gemini-2.5-flash",
    contents="آخرین پیشرفت‌ها در محاسبات کوانتومی چیست؟",
    config=types.GenerateContentConfig(
        tools=[types.Tool(google_search=types.GoogleSearch())]
    ),
)

print(response.text)

# دسترسی به متادیتای پایه‌گذاری برای استنادات
if response.candidates[0].grounding_metadata:
    metadata = response.candidates[0].grounding_metadata
    print(f"پرس‌وجوهای جستجوی استفاده‌شده: {metadata.web_search_queries}")
    for chunk in metadata.grounding_chunks:
        print(f"منبع: {chunk.web.title} - {chunk.web.uri}")

استفاده با SDK Google GenAI (JavaScript)

javascript
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
    apiKey: process.env.AVALAI_API_KEY,
    httpOptions: {"apiVersion": "v1beta", "baseUrl": "https://api.avalai.ir"}
});

const response = await ai.models.generateContent({
    model: "gemini-2.5-flash",
    contents: "آخرین پیشرفت‌ها در محاسبات کوانتومی چیست؟",
    config: {
        tools: [{ googleSearch: {} }]
    }
});

console.log(response.text);

// دسترسی به متادیتای پایه‌گذاری
const metadata = response.candidates[0].groundingMetadata;
if (metadata) {
    console.log("پرس‌وجوهای جستجو:", metadata.webSearchQueries);
    metadata.groundingChunks.forEach(chunk => {
        console.log(`منبع: ${chunk.web.title} - ${chunk.web.uri}`);
    });
}

پاسخ متادیتای پایه‌گذاری

API بومی اطلاعات پایه‌گذاری دقیقی برمی‌گرداند:

json
{
  "candidates": [
    {
      "content": {
        "parts": [{"text": "پیشرفت‌های اخیر در محاسبات کوانتومی شامل..."}],
        "role": "model"
      },
      "groundingMetadata": {
        "webSearchQueries": ["آخرین پیشرفت‌های محاسبات کوانتومی ۲۰۲۴"],
        "groundingChunks": [
          {"web": {"uri": "https://...", "title": "عنوان منبع"}}

          ],
          "groundingSupports": [
            {
              "segment": {"startIndex": 0, "endIndex": 100, "text": "..."},
              "groundingChunkIndices": [0]
            }
          ]
        }
      }
    ]
  }

برای جزئیات بیشتر درباره استفاده از API بومی Gemini با AvalAI، مرجع API v1beta را ببینید.

جستجو با مدل‌های Alibaba (Qwen)

مدل‌های فعلی Qwen شرکت Alibaba از جستجوی وب از طریق پارامتر enable_search با استراتژی agent پشتیبانی می‌کنند. این امکان به مدل‌هایی مانند qwen3.7-max، qwen3.7-plus و qwen3.6-flash اجازه می‌دهد به اطلاعات بلادرنگ از وب دسترسی داشته باشند.

توجه

برای مناطق بین‌المللی، search_strategy را روی agent تنظیم کنید. اسنپ‌شات‌های قدیمی‌تر qwen3-max ممکن است همچنان کار کنند، اما برای یکپارچه‌سازی‌های جدید از شناسه‌های فعلی Qwen3.7 یا Qwen3.6 استفاده کنید.

bash
curl -X POST https://api.avalai.ir/v1/chat/completions \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.7-max",
    "messages": [
        {
            "role": "user",
            "content": "قیمت سهام علی‌بابا چقدر است"
        }
    ],
    "enable_search": true,
    "search_options": {"search_strategy": "agent"}
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="qwen3.7-max",
    messages=[{"role": "user", "content": "پیش‌بینی آب‌وهوا برای فردا در تهران چیست؟"}],
    extra_body={"enable_search": True, "search_options": {"search_strategy": "agent"}},
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "qwen3.7-max",
  messages: [
    { role: "user", content: "آخرین اخبار فناوری امروز چیست؟" }
  ],
  enable_search: true,
  search_options: { search_strategy: "agent" }
});

// چاپ پاسخ
console.log(response.choices[0].message.content);
php
<?php

require 'vendor/autoload.php';

$apiKey = getenv('AVALAI_API_KEY');

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

$customBaseUrl = 'https://api.avalai.ir/v1';

$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

$completion = $client->chat()->create([
 'model' => 'qwen3.7-max',
 'messages' => [
  [
   'role' => 'user',
   'content' => 'قیمت فعلی سهام تسلا چقدر است؟'
  ]
 ],
 'enable_search' => true,
 'search_options' => ['search_strategy' => 'agent']
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;
نسخه معادل Responses API مدل این نسخه روی `gpt-5.5` تنظیم شده، چون `qwen3.7-max` ممکن است در داده‌های فعلی AvalAI برای `/v1/responses` فعال نباشد.

وقتی مدل انتخابی از /v1/responses پشتیبانی می‌کند، این نسخه را کنار مثال Chat Completions استفاده کنید. messages به input منتقل می‌شود و متن نهایی از response.output_text خوانده می‌شود.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.5",
    instructions="You are a helpful assistant.",
    input="آخرین اخبار فناوری امروز چیست؟",
)

print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-5.5",
  instructions: "You are a helpful assistant.",
  input: "آخرین اخبار فناوری امروز چیست؟",
});

console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.5",
    "input": "آخرین اخبار فناوری امروز چیست؟",
    "instructions": "You are a helpful assistant."
  }'
  • messagesinput
  • پیام سیستمی → instructions یا آیتم developer
  • choices[0].message.contentresponse.output_text
  • برای ابزارها و خروجی‌های چندوجهی، response.output را بر اساس type بررسی کنید.

پارامترهای کلیدی:

پارامترنوعتوضیحات
enable_searchbooleanبرای فعال‌سازی جستجوی وب روی true تنظیم کنید
search_options.search_strategystringباید برای مناطق بین‌المللی روی "agent" تنظیم شود

صورتحساب: جستجوی وب با مدل‌های Alibaba شامل هزینه‌های فراخوانی مدل (افزایش توکن‌های ورودی از نتایج جستجو) به علاوه هزینه‌های سیاست جستجو (۱۰.۰۰ دلار به ازای هر ۱٬۰۰۰ فراخوانی برای استراتژی agent در مناطق بین‌المللی) است.

ویژگی‌های پیشرفته جستجوی وب

انواع جستجوی وب

مدل‌های OpenAI از سه نوع اصلی جستجوی وب پشتیبانی می‌کنند:

۱. جستجوی وب غیراستدلالی

مدل پرس‌وجوی کاربر را به ابزار جستجوی وب ارسال می‌کند که پاسخ را بر اساس نتایج برتر برمی‌گرداند. این روش سریع است و برای جستجوهای سریع ایده‌آل است.

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-5.5",
 "tools": [{"type": "web_search"}],
 "input": "آب و هوای فعلی لندن چگونه است؟"
}'
python
import requests

url = "https://api.avalai.ir/v1/responses"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer $AVALAI_API_KEY",
}

data = {
    "model": "gpt-5.5",
    "tools": [{"type": "web_search"}],
    "input": "آب و هوای فعلی لندن چگونه است؟",
}

response = requests.post(url, headers=headers, json=data)
javascript
import fetch from 'node-fetch';

const response = await fetch('https://api.avalai.ir/v1/responses', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer $AVALAI_API_KEY',
  },
  body: JSON.stringify({
    model: 'gpt-5.5',
    tools: [{ type: 'web_search' }],
    input: 'آب و هوای فعلی لندن چگونه است؟',
  }),
});

const data = await response.json();

۲. جستجوی عاملی با مدل‌های استدلالی

مدل فرآیند جستجو را به طور فعال مدیریت می‌کند و جستجوهای وب را به عنوان بخشی از زنجیره تفکر خود انجام می‌دهد.

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-5.5",
 "reasoning": {"effort": "medium"},
 "tools": [{"type": "web_search"}],
 "input": "آخرین داده‌های فروش خودروهای برقی را در بازارهای مختلف مقایسه کن"
}'
python
import requests

data = {
    "model": "gpt-5.5",
    "reasoning": {"effort": "medium"},
    "tools": [{"type": "web_search"}],
    "input": "آخرین داده‌های فروش خودروهای برقی را در بازارهای مختلف مقایسه کن",
}

response = requests.post(url, headers=headers, json=data)

۳. تحقیق عمیق

روشی تخصصی برای بررسی‌های عمیق که اغلب از صدها منبع استفاده می‌کند و چندین دقیقه طول می‌کشد.

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "o3-deep-research",
 "tools": [{"type": "web_search", "search_context_size": "high"}],
 "input": "تحلیل جامعی از روندهای پذیرش انرژی تجدیدپذیر در سطح جهانی انجام دهید"
}'
python
import requests

data = {
    "model": "o3-deep-research",
    "tools": [{"type": "web_search", "search_context_size": "high"}],
    "input": "تحلیل جامعی از روندهای پذیرش انرژی تجدیدپذیر در سطح جهانی انجام دهید",
}

response = requests.post(url, headers=headers, json=data)

فیلتر کردن دامنه

نتایج جستجو را به دامنه‌های خاص با استفاده از پارامتر allowed_domains محدود کنید:

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-5.5",
 "tools": [{
   "type": "web_search",
   "filters": {
     "allowed_domains": [
       "pubmed.ncbi.nlm.nih.gov",
       "clinicaltrials.gov",
       "www.who.int",
       "www.cdc.gov"
     ]
   }
 }],
 "input": "تحقیقات اخیر در مورد درمان‌های کووید-۱۹ را پیدا کن"
}'
python
import requests

data = {
    "model": "gpt-5.5",
    "tools": [
        {
            "type": "web_search",
            "filters": {
                "allowed_domains": [
                    "pubmed.ncbi.nlm.nih.gov",
                    "clinicaltrials.gov",
                    "www.who.int",
                    "www.cdc.gov",
                ]
            },
        }
    ],
    "input": "تحقیقات اخیر در مورد درمان‌های کووید-۱۹ را پیدا کن",
}

response = requests.post(url, headers=headers, json=data)

موقعیت کاربر

نتایج جستجو را بر اساس موقعیت جغرافیایی بهبود بخشید:

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "o4-mini",
 "tools": [{
   "type": "web_search",
   "user_location": {
     "type": "approximate",
     "country": "US",
     "city": "San Francisco",
     "region": "California",
     "timezone": "America/Los_Angeles"
   }
 }],
 "input": "بهترین رستوران‌های ایتالیایی نزدیک من را پیدا کن"
}'
python
import requests

data = {
    "model": "o4-mini",
    "tools": [
        {
            "type": "web_search",
            "user_location": {
                "type": "approximate",
                "country": "US",
                "city": "San Francisco",
                "region": "California",
                "timezone": "America/Los_Angeles",
            },
        }
    ],
    "input": "بهترین رستوران‌های ایتالیایی نزدیک من را پیدا کن",
}

response = requests.post(url, headers=headers, json=data)

فیلد منابع

تمام URL های بازیابی شده در طول جستجوی وب را با استفاده از پارامتر include مشاهده کنید:

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-5.5",
 "tools": [{"type": "web_search"}],
 "include": ["web_search_call.action.sources"],
 "input": "آخرین پیشرفت‌ها در هوش مصنوعی"
}'
python
import requests

data = {
    "model": "gpt-5.5",
    "tools": [{"type": "web_search"}],
    "include": ["web_search_call.action.sources"],
    "input": "آخرین پیشرفت‌ها در هوش مصنوعی",
}

response = requests.post(url, headers=headers, json=data)

# دسترسی به منابع از پاسخ
sources = response.json()["web_search_call"]["action"]["sources"]
for source in sources:
    print(f"منبع: {source['url']} - {source.get('title', 'بدون عنوان')}")

کاربردهای رایج

جستجوی اخبار روز

مدل‌های مجهز به جستجوی وب، در ارائه آخرین اخبار و اطلاعات روز عملکرد بسیار خوبی دارند:

bash
curl https://api.avalai.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-4o-search-preview",
 "messages": [{
 "role": "user",
 "content": "What are the major headlines today?"
 }]
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="gpt-4o-search-preview",
    messages=[{"role": "user", "content": "What are the major headlines today?"}],
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-4o-search-preview",
  messages: [{ role: "user", content: "What are the major headlines today?" }],
});

// چاپ پاسخ
console.log(response.choices[0].message.content);
go
package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gpt-4o-search-preview",
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();		Role:    openai.ChatMessageRoleUser,
					Content: "What are the major headlines today?",
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}

	// چاپ پاسخ
	fmt.Println(resp.Choices[0].Message.Content)
}
php
<?php

require 'vendor/autoload.php';

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

$completion = $client->chat()->create([
 'model' => 'gpt-4o-search-preview',
 'messages' => [
 [
 'role' => 'user',
 'content' => 'What are the major headlines today?'
 ]
 ]
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;
نسخه معادل Responses API مدل این نسخه روی `gpt-5.5` تنظیم شده، چون `gpt-4o-search-preview` ممکن است در داده‌های فعلی AvalAI برای `/v1/responses` فعال نباشد.

وقتی مدل انتخابی از /v1/responses پشتیبانی می‌کند، این نسخه را کنار مثال Chat Completions استفاده کنید. messages به input منتقل می‌شود و متن نهایی از response.output_text خوانده می‌شود.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.5",
    instructions="You are a helpful assistant.",
    input="What are the major headlines today?",
)

print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-5.5",
  instructions: "You are a helpful assistant.",
  input: "What are the major headlines today?",
});

console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.5",
    "input": "What are the major headlines today?",
    "instructions": "You are a helpful assistant."
  }'
  • messagesinput
  • پیام سیستمی → instructions یا آیتم developer
  • choices[0].message.contentresponse.output_text
  • برای ابزارها و خروجی‌های چندوجهی، response.output را بر اساس type بررسی کنید.

پاسخ به پرسش‌های مبتنی بر واقعیت

این مدل‌ها قادرند به پرسش‌های واقعی، پاسخ‌هایی همراه با ارجاع به منابع ارائه دهند:

bash
curl https://api.avalai.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-4o-search-preview",
 "messages": [{
 "role": "user",
 "content": "Who won the most recent Nobel Prize in Physics and what was their contribution?"
 }]
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="gpt-4o-search-preview",
    messages=[
        {
            "role": "user",
            "content": "Who won the most recent Nobel Prize in Physics and what was their contribution?",
        }
    ],
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-4o-search-preview",
  messages: [
    {
      role: "user",
      content:
        "Who won the most recent Nobel Prize in Physics and what was their contribution?",
    },
  ],
});

// چاپ پاسخ
console.log(response.choices[0].message.content);
go
package main

import (
	"context"
	"fmt"
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();
func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gpt-4o-search-preview",
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "Who won the most recent Nobel Prize in Physics and what was their contribution?",
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();
	// چاپ پاسخ
	fmt.Println(resp.Choices[0].Message.Content)
}
php
<?php

require 'vendor/autoload.php';

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

$completion = $client->chat()->create([
 'model' => 'gpt-4o-search-preview',
 'messages' => [
 [
 'role' => 'user',
 'content' => 'Who won the most recent Nobel Prize in Physics and what was their contribution?'
 ]
 ]
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;
نسخه معادل Responses API مدل این نسخه روی `gpt-5.5` تنظیم شده، چون `gpt-4o-search-preview` ممکن است در داده‌های فعلی AvalAI برای `/v1/responses` فعال نباشد.

وقتی مدل انتخابی از /v1/responses پشتیبانی می‌کند، این نسخه را کنار مثال Chat Completions استفاده کنید. messages به input منتقل می‌شود و متن نهایی از response.output_text خوانده می‌شود.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.5",
    instructions="You are a helpful assistant.",
    input="Who won the most recent Nobel Prize in Physics and what was their contribution?",
)

print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-5.5",
  instructions: "You are a helpful assistant.",
  input: "Who won the most recent Nobel Prize in Physics and what was their contribution?",
});

console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.5",
    "input": "Who won the most recent Nobel Prize in Physics and what was their contribution?",
    "instructions": "You are a helpful assistant."
  }'
  • messagesinput
  • پیام سیستمی → instructions یا آیتم developer
  • choices[0].message.contentresponse.output_text
  • برای ابزارها و خروجی‌های چندوجهی، response.output را بر اساس type بررسی کنید.

سفارشی‌سازی پارامترها

پارامترهای جستجو برای مدل‌های OpenAI

برای مدل‌های با قابلیت جستجوی داخلی، می‌توانید از پارامترهای استاندارد API استفاده کنید:

bash
curl https://api.avalai.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-4o-search-preview",
 "messages": [{
 "role": "user",
 "content": "What happened in the financial markets today?"
 }],
 "temperature": 0.2,
 "response_format": {"type": "text"}
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="gpt-4o-search-preview",
    messages=[
        {"role": "user", "content": "What happened in the financial markets today?"}
    ],
    temperature=0.2,  # دمای پایین‌تر برای پاسخ‌های واقعی‌تر
    response_format={"type": "text"},  # برای پاسخ‌های فقط متنی
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-4o-search-preview",
  messages: [
    { role: "user", content: "What happened in the financial markets today?" },
  ],
  temperature: 0.2, // دمای پایین‌تر برای پاسخ‌های واقعی‌تر
  response_format: { type: "text" }, // برای پاسخ‌های فقط متنی
});

// چاپ پاسخ
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();:package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gpt-4o-search-preview",
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "What happened in the financial markets today?",
				},
			},
			Temperature: 0.2, // دمای پایین‌تر برای پاسخ‌های واقعی‌تر
			ResponseFormat: &openai.ChatCompletionResponseFormat{
				Type: openai.ChatCompletionResponseFormatTypeText, // برای پاسخ‌های فقط متنی
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();
	// چاپ پاسخ
	fmt.Println(resp.Choices[0].Message.Content)
}
php
<?php

require 'vendor/autoload.php';

$client = OpenAI::client('your-avalai-api-key', [
 'base_url' => 'https://api.avalai.ir/v1'
]);

$completion = $client->chat()->create([
 'model' => 'gpt-4o-search-preview',
 'messages' => [
 [
 'role' => 'user',
 'content' => 'What happened in the financial markets today?'
 ]
 ],
 'temperature' => 0.2, // دمای پایین‌تر برای پاسخ‌های واقعی‌تر
 'response_format' => [
 'type' => 'text' // برای پاسخ‌های فقط متنی
 ]
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;
نسخه معادل Responses API مدل این نسخه روی `gpt-5.5` تنظیم شده، چون `gpt-4o-search-preview` ممکن است در داده‌های فعلی AvalAI برای `/v1/responses` فعال نباشد.

وقتی مدل انتخابی از /v1/responses پشتیبانی می‌کند، این نسخه را کنار مثال Chat Completions استفاده کنید. messages به input منتقل می‌شود و متن نهایی از response.output_text خوانده می‌شود.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.5",
    instructions="You are a helpful assistant.",
    input="What happened in the financial markets today?",
)

print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-5.5",
  instructions: "You are a helpful assistant.",
  input: "What happened in the financial markets today?",
});

console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.5",
    "input": "What happened in the financial markets today?",
    "instructions": "You are a helpful assistant."
  }'
  • messagesinput
  • پیام سیستمی → instructions یا آیتم developer
  • choices[0].message.contentresponse.output_text
  • برای ابزارها و خروجی‌های چندوجهی، response.output را بر اساس type بررسی کنید.

پارامترهای جستجو برای مدل‌های Gemini

برای مدل‌های Gemini، می‌توانید رفتار جستجو را از طریق پارامتر tools سفارشی‌سازی کنید:

bash
curl -i "https://api.avalai.ir/v1/chat/completions" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
 "model": "gemini-2.5-flash",
 "messages": [{"role": "user", "content": "What are the latest developments in quantum computing?"}],
 "tools": [
 {
 "googleSearch": {
 "detail_level": "high"
 }
 }
 ]
}'
python
from openai import OpenAI

client = OpenAI(api_key="your-avalai-api-key", base_url="https://api.avalai.ir/v1")

response = client.chat.completions.create(
    model="gemini-2.5-flash",
    messages=[
        {
            "role": "user",
            "content": "What are the latest developments in quantum computing?",
        }
    ],
    tools=[{"googleSearch": {"detail_level": "high"}}],
)

# چاپ پاسخ
print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gemini-2.5-flash",
  messages: [
    {
      role: "user",
      content: "What are the latest developments in quantum computing?",
    },
  ],
  tools: [
    {
      googleSearch: {
        detail_level: "high",
      },
    },
  ],
});

// چاپ پاسخ
console.log(response.choices[0].message.content);
go
package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("your-avalai-api-key")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gemini-2.5-flash",
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "What are the latest developments in quantum computing?",
				},
			},
			Tools: []openai.Tool{
$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your actual key: 'aa-YOUR_API_KEY'

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();			DetailLevel: "high",
					},
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}

	// چاپ پاسخ
	fmt.Println(resp.Choices[0].Message.Content)
}
php
<?php

require 'vendor/autoload.php';

$client = OpenAI::client('your-avalai-api-key', [
 'base_url' => 'https://api.avalai.ir/v1'
]);

$detailLevel = new stdClass();
$detailLevel->detail_level = "high";

$completion = $client->chat()->create([
 'model' => 'gemini-2.5-flash',
 'messages' => [
 [
 'role' => 'user',
 'content' => 'What are the latest developments in quantum computing?'
 ]
 ],
 'tools' => [
 ['googleSearch' => $detailLevel]
 ]
]);

// چاپ پاسخ
echo $completion->choices[0]->message->content;
نسخه معادل Responses API مدل این نسخه روی `gpt-5.5` تنظیم شده، چون `gemini-2.5-flash` ممکن است در داده‌های فعلی AvalAI برای `/v1/responses` فعال نباشد.

وقتی مدل انتخابی از /v1/responses پشتیبانی می‌کند، این نسخه را کنار مثال Chat Completions استفاده کنید. messages به input منتقل می‌شود و متن نهایی از response.output_text خوانده می‌شود.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

tools = [
    {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"],
            "additionalProperties": False,
        },
    }
]

response = client.responses.create(
    model="gpt-5.5",
    input="What are the latest developments in quantum computing?",
    tools=tools,
)

for item in response.output:
    if item.type == "function_call":
        print(item.name, item.arguments)
print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const tools = [
  {
    type: "function",
    name: "get_current_weather",
    description: "Get the current weather in a given location.",
    parameters: {
      type: "object",
      properties: { location: { type: "string" } },
      required: ["location"],
      additionalProperties: false,
    },
  },
];

const response = await client.responses.create({
  model: "gpt-5.5",
  input: "What are the latest developments in quantum computing?",
  tools,
});

for (const item of response.output) {
  if (item.type === "function_call") {
    console.log(item.name, item.arguments);
  }
}
console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.5",
    "input": "What are the latest developments in quantum computing?",
    "tools": [
      {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string"
            }
          },
          "required": [
            "location"
          ],
          "additionalProperties": false
        }
      }
    ]
  }'
  • messagesinput
  • پیام سیستمی → instructions یا آیتم developer
  • choices[0].message.contentresponse.output_text
  • برای ابزارها و خروجی‌های چندوجهی، response.output را بر اساس type بررسی کنید.

ارجاع به منابع در نتایج جستجو

فرمت‌های ارجاع به منابع

مدل‌های OpenAI بسته به اندپوینتی که استفاده می‌کنید، ارجاعات را در فرمت‌های گوناگونی ارائه می‌دهند:

  1. Chat Completions API: ارجاعات به صورت درون‌خطی (inline) در متن، معمولا به شکل هایپرلینک یا پانویس، نمایش داده می‌شوند.
  2. Responses API: ارجاعات در یک ساختار مشخص و با استفاده از حاشیه‌نویسی‌های (annotations) URL ارائه می‌گردند.

نمونه‌ای از یک ارجاع ساختاریافته در Responses API:

json
{
  "id": "msg_67c9fa077e288190af08fdffda2e34f20be649c1a5ff9609",
  "type": "message",
  "status": "completed",
  "role": "assistant",
  "content": [
    {
      "type": "output_text",
      "text": "On March 6, 2025, several news...",
      "annotations": [
        {
          "type": "url_citation",
          "start_index": 2606,
          "end_index": 2758,
          "url": "https://...",

          "title": "Title..."
        }
      ]
    }
  ]
}

نحوه پردازش ارجاعات

برای پردازش و استخراج ارجاعات در برنامه خود:

bash
# این یک مثال ساده‌شده است که نشان می‌دهد چگونه داده‌های استناد را از پاسخ API استخراج کنید
# در یک برنامه واقعی، شما پاسخ JSON را تجزیه می‌کنید
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
 "model": "gpt-5.5",
 "tools": [{"type": "web_search"}],
 "input": "What was a positive news story from today?"
}' | jq '.annotations[] | select(.type == "url_citation") | {url: .url, title: .title}'
python
# برای API پاسخ‌ها
response = client.responses.create(
 model="gpt-5.5",
 tools=[{"type": "web_search"}],
 input="What was a positive news story from today?"
)

# استخراج استنادات
content = response.output_text
annotations = response.annotations

for annotation in annotations:
 if annotation.type == "url_citation":
 url = annotation.url
 title = annotation.title
 start = annotation.start_index
 end = annotation.end_index
 
 # پردازش استناد بر اساس نیاز
 print(f"Citation: {title} - {url}")
javascript
// برای API پاسخ‌ها
const response = await client.responses.create({
  model: "gpt-5.5",
  tools: [{ type: "web_search" }],
  input: "What was a positive news story from today?",
});

// استخراج استنادات
const content = response.output_text;
const annotations = response.annotations;

for (const annotation of annotations) {
  if (annotation.type === "url_citation") {
    const url = annotation.url;
    const title = annotation.title;
    const start = annotation.start_index;
    const end = annotation.end_index;

    // پردازش استناد بر اساس نیاز
    console.log(`Citation: ${title} - ${url}`);
  }
}
go
// برای API پاسخ‌ها
resp, err := client.CreateResponse(
	context.Background(),
	openai.ResponseRequest{
		Model: "gpt-5.5",
		Tools: []openai.Tool{
			{
				Type: "web_search",
			},
		},
		Input: "What was a positive news story from today?",
	},
)

if err != nil {
	fmt.Printf("Response error: %v\n", err)
	return
}

// استخراج استنادات
content := resp.OutputText
annotations := resp.Annotations

for _, annotation := range annotations {
	if annotation.Type == "url_citation" {
		url := annotation.URL
		title := annotation.Title
		start := annotation.StartIndex
		end := annotation.EndIndex

		// پردازش استناد بر اساس نیاز
		fmt.Printf("Citation: %s - %s\n", title, url)
	}
}
php
<?php
// برای API پاسخ‌ها
$response = $client->responses()->create([
 'model' => 'gpt-5.5',
 'tools' => [['type' => 'web_search']],
 'input' => 'What was a positive news story from today?'
]);

// استخراج استنادات
$content = $response->output_text;
$annotations = $response->annotations;

foreach ($annotations as $annotation) {
 if ($annotation->type === 'url_citation') {
 $url = $annotation->url;
 $title = $annotation->title;
 $start = $annotation->start_index;
 $end = $annotation->end_index;
 
 // پردازش استناد بر اساس نیاز
 echo "Citation: {$title} - {$url}\n";
 }
}

نکات و بهترین شیوه‌ها

  1. پرسش‌های دقیق مطرح کنید: به روشنی مشخص کنید که دقیقا به دنبال چه اطلاعاتی هستید.
  2. صراحتا درخواست منابع کنید: برای دریافت ارجاعات قابل اعتمادتر، عبارتی مانند «لطفا منابع را ذکر کن» را در پرامپت خود بیاورید.
  3. از temperature پایین استفاده کنید: برای دریافت پاسخ‌های واقعی‌تر و کمتر خلاقانه، مقدار temperature را بین 0.1 تا 0.3 تنظیم کنید.
  4. در صورت نیاز، به تاریخ اشاره کنید: عباراتی مانند «تا به امروز» یا «آخرین اطلاعات موجود» را در پرسش خود بگنجانید.
  5. اطلاعات حیاتی را مجددا بررسی کنید: صحت اطلاعات بسیار مهم را با مراجعه به چندین منبع تایید کنید.
  6. ترکیب دانش مدل و نتایج جستجو: از توانایی‌های مدل در کنار قابلیت جستجو به صورت ترکیبی بهره ببرید.

قیمت‌گذاری

هزینه استفاده از قابلیت جستجوی وب به مدل انتخابی و همچنین «اندازه زمینه جستجو» (Search Context Size) بستگی دارد:

مدلاندازه زمینه جستجوهزینه
gpt-5.5، gpt-4o یا gpt-4o-search-previewکم30.00$ برای هر 1000 فراخوانی
gpt-5.5، gpt-4o یا gpt-4o-search-previewمتوسط (پیش‌فرض)35.00$ برای هر 1000 فراخوانی
gpt-5.5، gpt-4o یا gpt-4o-search-previewزیاد50.00$ برای هر 1000 فراخوانی
gpt-5-mini، gpt-4o-mini یا gpt-4o-mini-search-previewکم25.00$ برای هر 1000 فراخوانی
gpt-5-mini، gpt-4o-mini یا gpt-4o-mini-search-previewمتوسط (پیش‌فرض)27.50$ برای هر 1000 فراخوانی
gpt-5-mini، gpt-4o-mini یا gpt-4o-mini-search-previewزیاد30.00$ برای هر 1000 فراخوانی
gemini-2.5-flash و سایر مدل‌های Geminiهمه سطوحمشابه قیمت‌گذاری OpenAI

عیب‌یابی

مشکلات متداول

  1. عدم انجام جستجو در مواقع مورد انتظار:

    • اطمینان حاصل کنید که پرسش شما نیازمند اطلاعاتی فراتر از دانش داخلی مدل است.
    • سعی کنید نیاز به اطلاعات به‌روز را صریح‌تر در پرامپت خود بیان کنید.
    • بررسی کنید که از مدل و پیکربندی صحیحی استفاده می‌کنید.
  2. ارجاعات ناقص یا ناموجود:

    • درخواست ذکر منابع را به طور واضح در پرامپت خود مطرح کنید.
    • برای دریافت متادیتای ساختاریافته ارجاعات، از Responses API استفاده کنید.
    • استفاده از تنظیمات بالاتر برای «اندازه زمینه جستجو» را مد نظر قرار دهید.
  3. نتایج جستجوی متناقض:

    • نتایج جستجو ممکن است بسته به زمان، موقعیت جغرافیایی و رفتار موتور جستجو متغیر باشند.
    • برای دستیابی به نتایج یکسان در طول آزمایش، می‌توانید پاسخ‌های جستجو را شبیه‌سازی (mock) کنید.
  4. برخورد با محدودیت نرخ (Rate Limiting):

    • فراخوانی‌های مربوط به جستجوی وب ممکن است دارای محدودیت نرخ متفاوتی نسبت به سایر فراخوانی‌های API باشند.
    • برای برنامه‌هایی با حجم درخواست بالا، استراتژی‌های مناسبی برای تلاش مجدد با تاخیر (backoff) پیاده‌سازی کنید.
  5. هزینه‌های بالا:

    • «اندازه زمینه جستجو» را متناسب با نیاز خود انتخاب کنید.
    • نتایج جستجوهای پرتکرار را کش (cache) کنید.
    • برای پرسش‌های ساده‌تر، از مدل‌های کوچک‌تر (mini) استفاده نمایید.

محدودیت‌ها

  • ممکن است نتایج جستجو همیشه کاملا با پرسش مرتبط نباشند.
  • ارجاعات گاهی اوقات ممکن است ناقص یا نادرست باشند.
  • مدل‌ها ممکن است دانش داخلی خود را با نتایج جستجو ترکیب کنند.
  • قابلیت‌های جستجو عمدتا برای پرسش‌های به زبان انگلیسی بهینه‌سازی شده‌اند.
  • کیفیت نتایج به در دسترس بودن و عملکرد موتور جستجو وابسته است.
  • تمام اطلاعات موجود در وب از طریق این قابلیت قابل دسترسی نیستند.

جمع‌بندی

قابلیت جستجوی وب با فراهم آوردن دسترسی به اطلاعات روز و داده‌های واقعی همراه با ارجاع به منابع، به طور چشمگیری عملکرد مدل‌های زبانی بزرگ را ارتقا می‌بخشد. با انتخاب مدل و رویکرد متناسب با نیاز خود، می‌توانید برنامه‌هایی بسازید که قدرت استدلال LLM‌ها را با اطلاعات لحظه‌ای وب ترکیب می‌کنند.

پیوندهای مرتبط