# JavaScript SDK

我们提供一个 JavaScript SDK，可无缝与 [Oxylabs AI Studio API](https://aistudio.oxylabs.io/) 服务，包括 AI-Scraper、AI-Crawler、AI-Browser-Agent 以及其他数据提取工具。

## 安装

安装 SDK：

```sh
npm install oxylabs-ai-studio
```

可以将 `OXYLABS_AI_STUDIO_API_URL` 并 `OXYLABS_AI_STUDIO_API_KEY` 的值添加到 `.env` 文件中，或者作为你的环境变量：

```sh
export OXYLABS_AI_STUDIO_API_KEY=your_api_key_here
```

## <sup>用法</sup>

### AI-Scraper

```javascript
import { 
  OxylabsAIStudioSDK
} from 'oxylabs-ai-studio';

const sdk = new OxylabsAIStudioSDK({
  apiKey: 'your_api_key_here',
  timeout: 120000,
  retryAttempts: 3,
});

async function testGenerateSchema() {
  try {
    console.log('测试 schema 生成...');
    const schema = await sdk.aiScraper.generateSchema({
      user_prompt: '提取页面标题'
    });
    console.log('Schema:', schema);
  } catch (error) {
    console.error('Schema 生成错误：', error.message);
  }
}

testGenerateSchema();
```

#### 基本用法

```javascript
import { 
  OxylabsAIStudioSDK, 
  OutputFormat
} from 'oxylabs-ai-studio';

const sdk = new OxylabsAIStudioSDK({
  apiKey: 'your_api_key_here',
  timeout: 120000,
  retryAttempts: 3,
});

async function testScrapeOutputJson() {
  try {
    console.log('测试带 JSON 输出的同步抓取...');
    
    const options = {
      url: 'https://www.freelancer.com',
      user_prompt: '提取所有链接',
      output_format: OutputFormat.JSON,
      geo_location: "US",
      schema: {
        type: 'object',
        properties: {
          links: { type: 'array', items: { type: 'string' } }
        }
      }
    };
    
    const results = await sdk.aiScraper.scrape(options);
    console.log('同步抓取结果：', results);
  } catch (error) {
    console.error('同步抓取错误：', error.message);
  }
}

testScrapeOutputJson();
```

#### 输入参数

* `url` (*string*）：要处理的目标 URL。
* `user_prompt` (*string*）：关于要提取哪些数据的说明。这将用于自动生成 `openapi_schema` ，在使用 `scrapeWithAutoSchema` 方法时。
* `output_format` (*string*）：所需的输出格式。可以是 `markdown` 或 `json`。默认值为 `markdown`.
* `render_html` (*boolean*）：指定在提取之前是否在页面上渲染 JavaScript。默认值为 `false`.
* `openapi_schema` (*Record\<string, any>*）：定义输出数据结构的 JSON Schema 对象。当 `output_format` 被设置为 `json`.
* `geo_location` (*string*）：指定请求应模拟的地理位置（ISO2 格式）。

### AI-Crawler

#### 基本用法

```javascript
import { 
  OxylabsAIStudioSDK, 
  OutputFormat
} from 'oxylabs-ai-studio';

const sdk = new OxylabsAIStudioSDK({
  apiKey: 'your_api_key_here',
  timeout: 120000,
  retryAttempts: 3,
});

async function testCrawlOutputJson() {
  try {
    console.log('测试带 JSON 输出的爬取...');
    
    const options = {
      url: 'https://www.freelancer.com',
      output_format: OutputFormat.JSON,
      user_prompt: '获取职位广告页面',
      return_sources_limit: 3,
      geo_location: "DE",
      schema: {
        type: "object",
        properties: {
          jobAd: {
            type: "object",
            properties: {
              position_title: {
                type: "string"
              },
              salary: {
                type: "string"
              }
            }
          }
        }
      }
    };
    
    const results = await sdk.aiCrawler.crawl(options);
    console.log('爬取结果：', JSON.stringify(results, null, 2));      
  } catch (error) {
    console.error('爬取错误：', error.message);
  }
}

testCrawlOutputJson();
```

#### 输入参数

* `url` (*string*）：爬取的起始 URL。
* `crawl_prompt` (*string*）：定义要查找并爬取的页面类型的说明。
* `parse_prompt` (*string*）：关于从爬取页面中提取哪些数据的说明。这将用于自动生成 `openapi_schema` ，在使用 `crawlWithAutoSchema` 方法时。
* `output_format` (*string*）：所需的输出格式。可以是 `markdown` 或 `json`。默认值为 `markdown`.
* `max_pages` (*integer*）：要返回的最大页面或来源数量。默认值为 `25`.
* `render_html` (*boolean*）：指定在提取之前是否在页面上渲染 JavaScript。默认值为 `false`.
* `openapi_schema` (*Record\<string, any>*）：定义输出数据结构的 JSON Schema 对象。当 `output_format` 被设置为 `json`.
* `geo_location` (*string*）：指定请求应模拟的地理位置（ISO2 格式）。

### Browser-Agent

#### 基本用法

```javascript
import { 
  OxylabsAIStudioSDK, 
  OutputFormat
} from 'oxylabs-ai-studio';

const sdk = new OxylabsAIStudioSDK({
  apiKey: 'your_api_key_here',
  timeout: 120000,
  retryAttempts: 3,
});

async function testBrowseOutputJson() {
  try {
    console.log('测试带 JSON 输出的同步浏览...');
    
    const options = {
      url: 'https://www.freelancer.com',
      output_format: OutputFormat.JSON,
      user_prompt: '前往你能找到的第一个职位广告。',
      geo_location: "US",
      schema: {
        type: 'object',
        properties: {
          job_title: { type: 'string' }
        }
      }
    };
    
    const results = await sdk.browserAgent.browse(options);
    console.log('同步浏览结果：', JSON.stringify(results, null, 2));
  } catch (error) {
    console.error('同步浏览错误：', error.message);
  }
}

testBrowseOutputJson();
```

#### 输入参数

* `url` (*string*）：浏览代理要开始访问的目标 URL。
* `browse_prompt` (*string*）：定义浏览代理应执行哪些操作的说明。
* `parse_prompt` (*string*）：在执行浏览操作后要提取哪些数据的说明。这将用于自动生成 `openapi_schema` ，在使用 `browseWithAutoSchema` 方法时。
* `output_format` (*string*）：所需的输出格式。可以是 `markdown`, `html`, `json`，或 `screenshot`。默认值为 `markdown`.
* `render_html` (*boolean*）：指定是否在页面上渲染 JavaScript。尽管这是一个浏览代理，但此标志可能会影响某些行为。默认值为 `false`.
* `openapi_schema` (*Record\<string, any>*）：定义输出数据结构的 JSON Schema 对象。当 `output_format` 被设置为 `json`.
* `geo_location` (*string*）：指定请求应模拟的地理位置（ISO2 格式）。

### AI-Search

#### 基本用法

```javascript
import {
  OxylabsAIStudioSDK,
} from 'oxylabs-ai-studio';

const sdk = new OxylabsAIStudioSDK({
  apiKey: 'your_api_key_here',
  timeout: 120000,
  retryAttempts: 3,
});

async function testSearch() {
  try {
    console.log('测试搜索...');

    const options = {
      query: 'weather in London',
      limit: 3,
      return_content: true,
      render_javascript: false,
      geo_location: "IT",
    };

    const results = await sdk.aiSearch.search(options);
    console.log('搜索结果：', JSON.stringify(results, null, 2));
  } catch (error) {
    console.error('搜索错误：', error.message);
  }
}

testSearch();
```

#### 输入参数

* `query` (*string*）：搜索查询。
* `limit` (*integer*）：要返回的搜索结果最大数量。最大值：50。
* `render_javascript` (*boolean*）：是否渲染页面上的 JavaScript。默认值为 `false`.
* `return_content` (*boolean*）：是否返回每个搜索结果的 Markdown 内容。默认值为 `true`.
* `geo_location` (*string*）：指定请求应模拟的地理位置（ISO2 格式）。

### AI-Map

#### 基本用法

```javascript
import { 
  OxylabsAIStudioSDK
} from 'oxylabs-ai-studio';

const sdk = new OxylabsAIStudioSDK({
  apiKey: 'your_api_key_here',
  timeout: 120000,
  retryAttempts: 3,
});

async function testMap() {
  try {
    console.log('测试地图...');
    
    const options = {
      url: 'https://www.freelancer.com/jobs',
      user_prompt: '提取技术职位广告',
      return_sources_limit: 10,
      geo_location: 'US',
      render_javascript: false
    };
    
    const results = await sdk.aiMap.map(options);
    console.log('地图结果：', JSON.stringify(results, null, 2));
  } catch (error) {
    console.error('地图错误：', error.message);
  }
}

testMap();
```

#### 输入参数

* `url` (*string*）：要进行映射并从中提取数据的目标 URL。
* `user_prompt` (*string*）：关于要从映射页面中提取哪些数据的说明。
* `return_sources_limit` (*integer*）：映射过程中要返回的最大来源/页面数量。
* `geo_location` (*string*）：用于映射请求的地理位置（例如 'US'、'UK'）。
* `render_javascript` (*boolean*）：指定在映射之前是否在页面上渲染 JavaScript。默认值为 `false`.

### 用法示例

你可以在这里找到更多每个应用的示例：

* [Browser-agent 示例](https://github.com/oxylabs/oxylabs-ai-studio-js/blob/main/examples/browser-agent.js)
* [AI-Crawler 示例](https://github.com/oxylabs/oxylabs-ai-studio-js/blob/main/examples/ai-crawler.js)
* [AI-Scraper 示例](https://github.com/oxylabs/oxylabs-ai-studio-js/blob/main/examples/ai-scraper.js)
* [AI-Search 示例](https://github.com/oxylabs/oxylabs-ai-studio-js/blob/main/examples/ai-search.js)
* [AI-Map 示例](https://github.com/oxylabs/oxylabs-ai-studio-js/blob/main/examples/ai-map.js)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developers.oxylabs.io/integrations/cn/ai-studio-integrations/javascript-sdk.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
