Al generar respuestas del modelo o crear agentes, puedes ampliar sus capacidades con herramientas integradas, llamadas a funciones, llamadas programáticas a herramientas, búsqueda de herramientas y servidores MCP remotos. Estas opciones permiten al modelo buscar en la web, recuperar información de tus archivos, cargar definiciones de herramientas de forma diferida durante la ejecución, llamar a tus propias funciones, combinar llamadas a herramientas en JavaScript o acceder a servicios de terceros. Solo gpt-5.4 y los modelos posteriores admiten tool_search.
Elige la integración para tu entorno de ejecución: configura las herramientas en las solicitudes a la API Responses , en los agentes de la API de agentes o en las definiciones del SDK de agentes . La disponibilidad y la configuración de las herramientas, así como el manejo de las llamadas, dependen de la integración. Los siguientes ejemplos usan la API Responses.
Búsqueda web Búsqueda de archivos Búsqueda de herramientas Llamada a funciones MCP remoto Búsqueda 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 Búsqueda de archivos
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) Búsqueda de herramientas
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) Llamada a funciones
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)
Esta es una descripción general de las herramientas disponibles en la plataforma de OpenAI. Selecciona una para obtener más información sobre su uso.
Llama a código personalizado para dar al modelo acceso a datos y
capacidades adicionales.
Incluye datos de Internet al generar respuestas del modelo.
Dale al modelo acceso a nuevas capacidades mediante servidores de
Model Context Protocol (MCP).
Sube y reutiliza paquetes de habilidades con versiones en entornos de shell alojados en la nube.
Ejecuta comandos de shell en contenedores alojados en la nube o en tu propio entorno de ejecución local.
Crea flujos de trabajo con agentes que permitan a un modelo controlar la interfaz de una
computadora.
Genera o edita imágenes con GPT Image.
Busca en el contenido de los archivos subidos para obtener contexto al generar una
respuesta.
Carga dinámicamente herramientas relevantes en el contexto del modelo para optimizar el uso de
tokens.
Llamada programática a herramientas
Permite que los modelos escriban y ejecuten código JavaScript que orqueste llamadas a herramientas.
Al realizar una solicitud para generar una respuesta del modelo , normalmente habilitas el acceso a las herramientas especificando sus configuraciones en el parámetro tools. Cada herramienta tiene sus propios requisitos de configuración. Consulta la sección Herramientas disponibles para obtener instrucciones detalladas.
Según el prompt proporcionado, el modelo decide automáticamente si debe usar una herramienta configurada. Por ejemplo, si tu prompt solicita información posterior a la fecha de corte del entrenamiento del modelo y la búsqueda web está habilitada, el modelo normalmente invocará la herramienta de búsqueda web para recuperar información relevante y actualizada.
Algunos flujos de trabajo avanzados también pueden cargar más definiciones de herramientas durante la interacción. Por ejemplo, la búsqueda de herramientas puede diferir la carga de las definiciones de funciones hasta que el modelo decida que las necesita.
Puedes controlar u orientar explícitamente este comportamiento configurando el parámetro tool_choice en la solicitud a la API .
La API de agentes ejecuta el bucle del agente por ti. Configura las herramientas en agent.tools, maneja las llamadas a funciones en tu aplicación y conecta un sandbox cuando las herramientas necesiten un entorno de ejecución.
Consulta Funciones para llamar al código de la aplicación, Conexiones MCP para conectar servidores de herramientas y la configuración del sandbox para las herramientas que necesitan un entorno de ejecución. La llamada programática a herramientas está habilitada de forma predeterminada. Las habilidades se detectan a través de los directorios de capacidades del sandbox.
En el Agents SDK, la semántica de las herramientas se mantiene, pero su integración se configura en la definición del agente y el diseño del flujo de trabajo, en lugar de hacerlo en una única solicitud a la API Responses.
Agrega herramientas alojadas en la nube, herramientas de función o herramientas MCP alojadas en la nube directamente al agente cuando un especialista deba llamarlas por sí mismo.
Expón un especialista como herramienta cuando un agente coordinador deba mantener el control de la respuesta al usuario.
Mantén los arneses de ejecución de shell, aplicación de parches y uso de la computadora en tu entorno de ejecución, incluso cuando el SDK modele la decisión de usar una herramienta.
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.",
)
],
)
Consulta Definiciones de agentes cuando estés definiendo un solo especialista, Orquestación y transferencias cuando las herramientas afecten quién asume la responsabilidad, Medidas de protección y revisión humana cuando las herramientas afecten las aprobaciones e Integraciones y observabilidad cuando la capacidad provenga de MCP.