Ao gerar respostas do modelo ou criar agentes, você pode ampliar suas capacidades usando ferramentas integradas, chamada de função, chamada programática de ferramentas, pesquisa de ferramentas e servidores MCP remotos. Esses recursos permitem que o modelo pesquise na Web, recupere informações dos seus arquivos, carregue definições de ferramentas sob demanda em tempo de execução, chame suas próprias funções, componha chamadas de ferramentas em JavaScript ou acesse serviços de terceiros. Apenas gpt-5.4 e modelos posteriores oferecem suporte a tool_search.
Escolha a integração para seu ambiente de execução: configure ferramentas nas solicitações à API Responses , nos agentes da API de Agentes ou nas definições do SDK de Agentes . A disponibilidade das ferramentas, a configuração e o tratamento das chamadas dependem da integração. Os exemplos abaixo usam a API Responses.
Pesquisa na Web Pesquisa de arquivos Pesquisa de ferramentas Chamada de função MCP remoto Pesquisa na Web
1
2
3
4
5
6
7
8
9
10 import OpenAI from "openai" ;
const client = new OpenAI ();
const response = await client.responses. create ({
model: "gpt-6-astra" ,
tools: [{ type: "web_search" }],
input: "What was a positive news story from today?" ,
});
console. log (response.output_text); 1
2
3
4
5
6
7
8
9
10
11 from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
tools=[{"type": "web_search"}],
input="What was a positive news story from today?",
)
print(response.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{
responses.ToolParamOfWebSearch(responses.WebSearchToolTypeWebSearch),
},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What was a positive news story from today?")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.WebSearchTool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What was a positive news story from today?")
.addTool(WebSearchTool.builder().type(WebSearchTool.Type.WEB_SEARCH).build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(ResponseTool.CreateWebSearchTool());
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("What was a positive news story from today?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText()); 1
2
3
4
5
6
7
8
9
10
11 require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6-astra",
tools: [{ type: "web_search" }],
input: "What was a positive news story from today?"
)
puts(response.output_text) 1
2
3
4
5
6
7
8 curl "https://api.openai.com/v1/responses" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6-astra",
"tools": [{"type": "web_search"}],
"input": "what was a positive news story from today?"
}' 1
2
3
4
5
6
7
8 openai responses create \
--model gpt-6-astra \
--raw-output \
--transform 'output.#(type=="message").content.0.text' <<'YAML'
tools:
- type: web_search
input: What was a positive news story from today?
YAML Pesquisa de arquivos
1
2
3
4
5
6
7
8
9
10
11
12
13
14 import OpenAI from "openai" ;
const openai = new OpenAI ();
const response = await openai.responses. create ({
model: "gpt-6-astra" ,
input: "What is deep research by OpenAI?" ,
tools: [
{
type: "file_search" ,
vector_store_ids: [ "<vector_store_id>" ],
},
],
});
console. log (response); 1
2
3
4
5
6
7
8
9
10 from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-astra",
input="What is deep research by OpenAI?",
tools=[{"type": "file_search", "vector_store_ids": ["<vector_store_id>"]}],
)
print(response) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is deep research by OpenAI?")},
Tools: []responses.ToolUnionParam{responses.ToolParamOfFileSearch([]string{"<vector_store_id>"})},
})
if err != nil {
panic(err)
}
fmt.Println(response)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import java.util.List;
String vectorStoreId = "<vector_store_id>";
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What is deep research by OpenAI?")
.addFileSearchTool(List.of(vectorStoreId))
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string vectorStoreId = "<vector_store_id>";
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(
ResponseTool.CreateFileSearchTool([vectorStoreId])
);
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("What is deep research by OpenAI?")
);
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6-astra",
input: "What is deep research by OpenAI?",
tools: [
{
type: "file_search",
vector_store_ids: ["<vector_store_id>"]
}
]
)
puts(response) Pesquisa de ferramentas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47 import OpenAI from "openai" ;
const client = new OpenAI ();
const crmNamespace = {
type: "namespace" ,
name: "crm" ,
description: "CRM tools for customer lookup and order management." ,
tools: [
{
type: "function" ,
name: "get_customer_profile" ,
description: "Fetch a customer profile by customer ID." ,
parameters: {
type: "object" ,
properties: {
customer_id: { type: "string" },
},
required: [ "customer_id" ],
additionalProperties: false ,
},
},
{
type: "function" ,
name: "list_open_orders" ,
description: "List open orders for a customer ID." ,
defer_loading: true ,
parameters: {
type: "object" ,
properties: {
customer_id: { type: "string" },
},
required: [ "customer_id" ],
additionalProperties: false ,
},
},
],
};
const response = await client.responses. create ({
model: "gpt-6-astra" ,
input: "List open orders for customer CUST-12345." ,
tools: [crmNamespace, { type: "tool_search" }],
parallel_tool_calls: false ,
});
console. log (response.output); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50 from openai import OpenAI
client = OpenAI()
crm_namespace = {
"type": "namespace",
"name": "crm",
"description": "CRM tools for customer lookup and order management.",
"tools": [
{
"type": "function",
"name": "get_customer_profile",
"description": "Fetch a customer profile by customer ID.",
"parameters": {
"type": "object",
"properties": {
"customer_id": {"type": "string"},
},
"required": ["customer_id"],
"additionalProperties": False,
},
},
{
"type": "function",
"name": "list_open_orders",
"description": "List open orders for a customer ID.",
"defer_loading": True,
"parameters": {
"type": "object",
"properties": {
"customer_id": {"type": "string"},
},
"required": ["customer_id"],
"additionalProperties": False,
},
},
],
}
response = client.responses.create(
model="gpt-6-astra",
input="List open orders for customer CUST-12345.",
tools=[
crm_namespace,
{"type": "tool_search"},
],
parallel_tool_calls=False,
)
print(response.output) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
parameters := map[string]any{
"type": "object",
"properties": map[string]any{"customer_id": map[string]any{"type": "string"}},
"required": []string{"customer_id"},
"additionalProperties": false,
}
namespace := responses.ToolParamOfNamespace(
"CRM tools for customer lookup and order management.",
"crm",
[]responses.NamespaceToolToolUnionParam{
{OfFunction: &responses.NamespaceToolToolFunctionParam{
Name: "get_customer_profile", Description: openai.String("Fetch a customer profile by customer ID."), Parameters: parameters,
}},
{OfFunction: &responses.NamespaceToolToolFunctionParam{
Name: "list_open_orders", Description: openai.String("List open orders for a customer ID."), DeferLoading: openai.Bool(true), Parameters: parameters,
}},
},
)
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("List open orders for customer CUST-12345.")},
Tools: []responses.ToolUnionParam{namespace, {OfToolSearch: &responses.ToolSearchToolParam{}}},
ParallelToolCalls: openai.Bool(false),
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.NamespaceTool;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ToolSearchTool;
import java.util.List;
import java.util.Map;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("List open orders for customer CUST-12345.")
.parallelToolCalls(false)
.addTool(
NamespaceTool.builder()
.name("crm")
.description("CRM tools for customer lookup and order management.")
.addTool(
NamespaceTool.Tool.Function.builder()
.name("get_customer_profile")
.description("Fetch a customer profile by customer ID.")
.strict(true)
.parameters(
JsonValue.from(
Map.of(
"type",
"object",
"properties",
Map.of("customer_id", Map.of("type", "string")),
"required",
List.of("customer_id"),
"additionalProperties",
false)))
.build())
.addTool(
NamespaceTool.Tool.Function.builder()
.name("list_open_orders")
.description("List open orders for a customer ID.")
.deferLoading(true)
.strict(true)
.parameters(
JsonValue.from(
Map.of(
"type",
"object",
"properties",
Map.of("customer_id", Map.of("type", "string")),
"required",
List.of("customer_id"),
"additionalProperties",
false)))
.build())
.build())
.addTool(ToolSearchTool.builder().execution(ToolSearchTool.Execution.SERVER).build())
.build();
client.responses().create(params).output().forEach(System.out::println); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39 require "openai"
client = OpenAI::Client.new
parameters = {
type: :object,
properties: { customer_id: { type: :string } },
required: ["customer_id"],
additionalProperties: false
}
response = client.responses.create(
model: "gpt-6-astra",
input: "List open orders for customer CUST-12345.",
parallel_tool_calls: false,
tools: [
{
type: :namespace,
name: "crm",
description: "CRM tools for customer lookup and order management.",
tools: [
{
type: :function,
name: "get_customer_profile",
description: "Fetch a customer profile by customer ID.",
parameters: parameters
},
{
type: :function,
name: "list_open_orders",
description: "List open orders for a customer ID.",
defer_loading: true,
parameters: parameters
}
]
},
{ type: :tool_search }
]
)
puts(response.output) Chamada de função
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 import OpenAI from "openai" ;
const client = new OpenAI ();
const tools = [
{
type: "function" ,
name: "get_weather" ,
description: "Get current temperature for a given location." ,
parameters: {
type: "object" ,
properties: {
location: {
type: "string" ,
description: "City and country e.g. Bogotá, Colombia" ,
},
},
required: [ "location" ],
additionalProperties: false ,
},
strict: true ,
},
];
const response = await client.responses. create ({
model: "gpt-6-astra" ,
input: [
{ role: "user" , content: "What is the weather like in Paris today?" },
],
tools,
});
console. log (response.output[ 0 ]); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33 from openai import OpenAI
client = OpenAI()
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia",
}
},
"required": ["location"],
"additionalProperties": False,
},
"strict": True,
},
]
response = client.responses.create(
model="gpt-6-astra",
input=[
{"role": "user", "content": "What is the weather like in Paris today?"},
],
tools=tools,
)
print(response.output[0].to_json()) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
parameters := map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]any{
"type": "string",
"description": "City and country e.g. Bogotá, Colombia",
},
},
"required": []string{"location"},
"additionalProperties": false,
}
tool := responses.ToolParamOfFunction("get_weather", parameters, true)
tool.OfFunction.Description = openai.String("Get current temperature for a given location.")
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage("What is the weather like in Paris today?", responses.EasyInputMessageRoleUser),
}},
Tools: []responses.ToolUnionParam{tool},
})
if err != nil {
panic(err)
}
fmt.Println(response.Output)
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.ResponseCreateParams;
import java.util.List;
import java.util.Map;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("What is the weather like in Paris today?")
.addTool(
FunctionTool.builder()
.name("get_weather")
.description("Get current temperature for a given location.")
.parameters(
FunctionTool.Parameters.builder()
.putAdditionalProperty("type", JsonValue.from("object"))
.putAdditionalProperty(
"properties",
JsonValue.from(
Map.of(
"location",
Map.of(
"type", "string",
"description",
"City and country e.g. Bogotá, Colombia"))))
.putAdditionalProperty("required", JsonValue.from(List.of("location")))
.putAdditionalProperty("additionalProperties", JsonValue.from(false))
.build())
.strict(true)
.build())
.build();
client.responses().create(params).output().forEach(System.out::println); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(
ResponseTool.CreateFunctionTool(
functionName: "get_weather",
functionDescription: "Get current temperature for a given location.",
functionParameters: BinaryData.FromString(
"""
{
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
}
},
"required": ["location"],
"additionalProperties": false
}
"""
),
strictModeEnabled: true
)
);
options.InputItems.Add(
ResponseItem.CreateUserMessageItem("What is the weather like in Paris today?")
);
ResponseResult response = await client.CreateResponseAsync(options);
foreach (ResponseItem outputItem in response.OutputItems)
{
if (outputItem is FunctionCallResponseItem functionCall)
{
Console.WriteLine(
$"{functionCall.FunctionName}({functionCall.FunctionArguments})"
);
}
else if (outputItem is MessageResponseItem message)
{
foreach (ResponseContentPart content in message.Content)
{
if (content.Kind == ResponseContentPartKind.OutputText)
{
Console.WriteLine(content.Text);
}
else if (content.Kind == ResponseContentPartKind.Refusal)
{
Console.WriteLine(content.Refusal);
}
}
}
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36 require "openai"
openai = OpenAI::Client.new
tools = [
{
type: "function",
name: "get_weather",
description: "Get current temperature for a given location.",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "City and country e.g. Bogotá, Colombia"
}
},
required: ["location"],
additionalProperties: false
},
strict: true
}
]
response = openai.responses.create(
model: "gpt-6-astra",
input: [
{
role: "user",
content: "What is the weather like in Paris today?"
}
],
tools: tools
)
puts(response.output.fetch(0).to_json) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 curl -X POST https://api.openai.com/v1/responses \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6-astra",
"input": [
{"role": "user", "content": "What is the weather like in Paris today?"}
],
"tools": [
{
"type": "function",
"name": "get_weather",
"description": "Get current temperature for a given location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City and country e.g. Bogotá, Colombia"
}
},
"required": ["location"],
"additionalProperties": false
},
"strict": true
}
]
}' MCP remoto
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY " \
-d '{
"model": "gpt-6-astra",
"tools": [
{
"type": "mcp",
"server_label": "dmcp",
"server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",
"server_url": "https://dmcp-server.deno.dev/mcp",
"require_approval": "never"
}
],
"input": "Roll 2d4+1"
}' 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import OpenAI from "openai";
const client = new OpenAI();
const resp = await client.responses.create({
model: "gpt-6-astra",
tools: [
{
type: "mcp",
server_label: "dmcp",
server_description:
"A Dungeons and Dragons MCP server to assist with dice rolling.",
server_url: "https://dmcp-server.deno.dev/mcp",
require_approval: "never",
},
],
input: "Roll 2d4+1",
});
console.log(resp.output_text); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 from openai import OpenAI
client = OpenAI()
resp = client.responses.create(
model="gpt-6-astra",
tools=[
{
"type": "mcp",
"server_label": "dmcp",
"server_description": "A Dungeons and Dragons MCP server to assist with dice rolling.",
"server_url": "https://dmcp-server.deno.dev/mcp",
"require_approval": "never",
},
],
input="Roll 2d4+1",
)
print(resp.output_text) 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
tool := responses.ToolParamOfMcp("dmcp")
tool.OfMcp.ServerDescription = openai.String("A Dungeons and Dragons MCP server to assist with dice rolling.")
tool.OfMcp.ServerURL = openai.String("https://dmcp-server.deno.dev/mcp")
tool.OfMcp.RequireApproval = responses.ToolMcpRequireApprovalUnionParam{OfMcpToolApprovalSetting: openai.String("never")}
response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Tools: []responses.ToolUnionParam{tool},
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Roll 2d4+1")},
})
if err != nil {
panic(err)
}
fmt.Println(response.OutputText())
} 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.Tool;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Roll 2d4+1")
.addTool(
Tool.Mcp.builder()
.serverLabel("dmcp")
.serverDescription(
"A Dungeons and Dragons MCP server to assist with dice rolling.")
.serverUrl("https://dmcp-server.deno.dev/mcp")
.requireApproval(Tool.Mcp.RequireApproval.McpToolApprovalSetting.NEVER)
.build())
.build();
client.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(text -> System.out.println(text.text())); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
CreateResponseOptions options = new() { Model = "gpt-6-astra" };
options.Tools.Add(
ResponseTool.CreateMcpTool(
serverLabel: "dmcp",
serverUri: new Uri("https://dmcp-server.deno.dev/mcp"),
toolCallApprovalPolicy: DefaultMcpToolCallApprovalPolicy.NeverRequireApproval
)
);
options.InputItems.Add(ResponseItem.CreateUserMessageItem("Roll 2d4+1"));
ResponseResult response = await client.CreateResponseAsync(options);
Console.WriteLine(response.GetOutputText()); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 require "openai"
openai = OpenAI::Client.new
response = openai.responses.create(
model: "gpt-6-astra",
tools: [
{
type: "mcp",
server_label: "dmcp",
server_description: "A Dungeons and Dragons MCP server to assist with dice rolling.",
server_url: "https://dmcp-server.deno.dev/mcp",
require_approval: "never"
}
],
input: "Roll 2d4+1"
)
puts(response.output_text)
Confira uma visão geral das ferramentas disponíveis na plataforma da OpenAI. Selecione uma delas para ver orientações de uso mais detalhadas.
Chame código personalizado para dar ao modelo acesso a dados e
capacidades adicionais.
Inclua dados da Internet na geração de respostas do modelo.
Dê ao modelo acesso a novas capacidades por meio de servidores
Model Context Protocol (MCP).
Envie e reutilize pacotes versionados de habilidades em ambientes de shell hospedado.
Execute comandos de shell em contêineres hospedados ou no seu próprio ambiente de execução local.
Crie fluxos de trabalho agênticos que permitam a um modelo controlar a interface de um
computador.
Gere ou edite imagens usando GPT Image.
Pesquise no conteúdo dos arquivos enviados para obter contexto ao gerar uma
resposta.
Carregue dinamicamente ferramentas relevantes no contexto do modelo para otimizar o uso de
tokens.
Chamada programática de ferramentas
Permita que os modelos escrevam e executem código JavaScript que orquestre chamadas de ferramentas.
Ao fazer uma solicitação para gerar uma resposta do modelo , você geralmente habilita o acesso a ferramentas especificando configurações no parâmetro tools. Cada ferramenta tem requisitos específicos de configuração. Consulte a seção Ferramentas disponíveis para obter instruções detalhadas.
Com base no prompt fornecido, o modelo decide automaticamente se deve usar uma ferramenta configurada. Por exemplo, se o seu prompt solicitar informações posteriores à data de corte do treinamento do modelo e a pesquisa na Web estiver habilitada, o modelo normalmente chamará a ferramenta de pesquisa na Web para recuperar informações relevantes e atualizadas.
Alguns fluxos de trabalho avançados também podem carregar mais definições de ferramentas durante a interação. Por exemplo, a pesquisa de ferramentas pode adiar o carregamento das definições de funções até que o modelo decida que elas são necessárias.
Você pode controlar ou orientar explicitamente esse comportamento definindo o parâmetro tool_choice na solicitação à API .
A API de Agentes executa o ciclo do agente para você. Configure ferramentas em agent.tools, trate as chamadas de função no seu aplicativo e conecte um sandbox quando as ferramentas precisarem de um ambiente de execução.
Consulte Funções para chamar código do aplicativo, Conexões MCP para conectar servidores de ferramentas e configuração do sandbox para ferramentas que precisam de um ambiente de execução. A Chamada programática de ferramentas está habilitada por padrão. As Habilidades são localizadas por meio dos diretórios de capacidades do sandbox.
No Agents SDK, a semântica das ferramentas permanece a mesma, mas a integração passa a fazer parte da definição do agente e do projeto do fluxo de trabalho, em vez de ficar em uma única solicitação à Responses API.
Adicione ferramentas hospedadas, ferramentas de função ou ferramentas MCP hospedadas diretamente ao agente quando um especialista precisar chamá-las por conta própria.
Exponha um especialista como ferramenta quando um gerente precisar manter o controle da resposta apresentada ao usuário.
Mantenha os harnesses de shell, aplicação de patches e uso do computador no seu ambiente de execução, mesmo quando o SDK modelar a decisão de usar uma ferramenta.
1
2
3
4
5
6
7
8
9
10
11 import { tool } from "@openai/agents" ;
import { z } from "zod" ;
const getWeatherTool = tool ({
name: "get_weather" ,
description: "Get the weather for a given city." ,
parameters: z. object ({ city: z. string () }),
async execute ({ city }) {
return `The weather in ${ city } is sunny.` ;
},
}); 1
2
3
4
5
6
7 from agents import function_tool
@function_tool
def get_weather(city: str) -> str:
"""Get the weather for a given city."""
return f"The weather in {city} is sunny."
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 import { Agent } from "@openai/agents" ;
const summarizer = new Agent ({
name: "Summarizer" ,
instructions: "Generate a concise summary of the supplied text." ,
});
const mainAgent = new Agent ({
name: "Research assistant" ,
tools: [
summarizer. asTool ({
toolName: "summarize_text" ,
toolDescription: "Generate a concise summary of the supplied text." ,
}),
],
}); 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 from agents import Agent
summarizer = Agent(
name="Summarizer",
instructions="Generate a concise summary of the supplied text.",
)
main_agent = Agent(
name="Research assistant",
tools=[
summarizer.as_tool(
tool_name="summarize_text",
tool_description="Generate a concise summary of the supplied text.",
)
],
)
Consulte Definições de agentes ao definir um único especialista, Orquestração e transferências quando as ferramentas afetarem a distribuição de responsabilidades, Mecanismos de proteção e revisão humana quando as ferramentas afetarem as aprovações e Integrações e observabilidade quando o recurso vier do MCP.