Usare lo strumento SharePoint con l'API agente (anteprima)

Importante

Gli elementi contrassegnati (anteprima) in questo articolo sono attualmente in anteprima pubblica. Questa anteprima viene fornita senza un contratto di servizio e non è consigliabile per i carichi di lavoro di produzione. Alcune funzionalità potrebbero non essere supportate o potrebbero avere funzionalità limitate. Per altre informazioni, vedere Condizioni supplementari per l'utilizzo delle anteprime di Microsoft Azure.

Nota

  • Questo articolo descrive lo strumento Microsoft SharePoint per il servizio agente Foundry. Per informazioni sull'uso e la distribuzione di siti di SharePoint, vedere la documentazione SharePoint.
  • Per informazioni sull'ottimizzazione dell'utilizzo degli strumenti, vedere Procedure consigliate .

Usare lo strumento di SharePoint (anteprima) per l'integrazione con SharePoint nel Servizio Agent Microsoft Foundry recuperando il contenuto da un sito o una cartella di SharePoint (ad esempio, contoso.sharepoint.com/sites/policies). Quando un utente pone una domanda, l'agente può richiamare lo strumento SharePoint per recuperare il testo pertinente dai documenti a cui l'utente può accedere. L'agente genera quindi una risposta basata sul contenuto recuperato.

Questa integrazione utilizza il pass-through delle identità (On-Behalf-Of) affinché le autorizzazioni di SharePoint siano applicate a ogni richiesta. Per informazioni dettagliate sull'integrazione dell'API di recupero Microsoft 365 Copilot sottostante, vedere Come funziona.

Importante

Prima di iniziare: lo strumento di SharePoint richiede l'autenticazione dell'identità utente (nessuna entità servizio/solo app), il sito SharePoint e l'agente Foundry devono trovarsi nello stesso tenant e è supportato un solo strumento di SharePoint per agente. Lo strumento non funziona quando l'agente viene pubblicato in Microsoft Teams. Vedere Limitazioni per l'elenco completo.

Prerequisiti

  • Licenza idonea o modello con pagamento in base al consumo:

    • Gli sviluppatori e gli utenti finali hanno una licenza di Microsoft 365 Copilot, come richiesto dall'API di recupero Microsoft 365 Copilot.
    • Se gli sviluppatori e gli utenti finali non hanno una licenza Microsoft 365 Copilot, è possibile abilitare il modello pay-as-you-go.
  • Gli sviluppatori e gli utenti finali hanno almeno Foundry User un ruolo RBAC assegnato nel progetto Foundry. Per altre informazioni sul controllo degli accessi in base al ruolo Azure, vedere Azure controllo degli accessi in base al ruolo in Foundry.

    Importante

    I ruoli di Controllo degli accessi in base al ruolo di Foundry sono stati recentemente rinominati. Foundry User, Foundry Owner, Foundry Account Owner e Foundry Project Manager erano precedentemente denominati Azure AI User, Azure AI Owner, Azure AI Account Owner e Azure AI Project Manager. È possibile che i nomi precedenti vengano visualizzati in alcune posizioni durante l'esecuzione della ridenominazione. Gli ID ruolo e le autorizzazioni di base sono invariati dalla ridenominazione.

  • Gli sviluppatori e gli utenti finali hanno almeno READ accesso al sito di SharePoint.

  • Assicurarsi che il tenant SharePoint e il progetto Foundry si trovino nello stesso tenant Microsoft Entra. Lo scambio di token tra tenant non è supportato.

  • Installare il pacchetto SDK necessario:

    • Python:pip install "azure-ai-projects>=2.0.0"
    • C#: Installare il pacchetto NuGet Azure.AI.Projects
    • TypeScript/JavaScript: npm install @azure/ai-projects
    • Java: Aggiungi la dipendenza più recente com.azure:azure-ai-agents al tuo pom.xml
  • Configurare le variabili di ambiente usate dall'esempio:

    • FOUNDRY_PROJECT_ENDPOINT: URL dell'endpoint del progetto Foundry
    • FOUNDRY_MODEL_DEPLOYMENT_NAME: nome della distribuzione del modello (ad esempio, gpt-4)
    • SHAREPOINT_PROJECT_CONNECTION_ID: ID connessione SharePoint nel formato /subscriptions/{{subscriptionID}}/resourceGroups/{{resourceGroupName}}/providers/Microsoft.CognitiveServices/accounts/{{foundryAccountName}}/projects/{{foundryProjectName}}/connections/{{foundryConnectionName}}
    • Per esempi REST: AGENT_TOKEN
  • Per altri dettagli sull'installazione dell'autenticazione, vedere la guida introduttiva .

Configurare la connessione SharePoint e l'utente delegato

Lo strumento SharePoint usa l'autenticazione utente delegata. Eseguire l'agente con l'identità dell'utente connesso in modo che SharePoint possa applicare le autorizzazioni dell'utente per il sito, la cartella e il documento. L'autenticazione tramite sola app e quella del service principal non sono supportate.

Nota

Iniziare con un sito SharePoint con una struttura di cartelle semplice e un numero ridotto di documenti brevi.

  1. Selezionare SharePoint e seguire le istruzioni per aggiungere lo strumento. È possibile aggiungere un solo strumento SharePoint per agente.
  2. Aggiungere una connessione SharePoint. Per il flusso di lavoro di connessione completo, vedere Aggiungere una nuova connessione al progetto.
  3. Nella configurazione della connessione SharePoint immettere l'URL del sito o l'URL della cartella:
  • URL sito: https://<company>.sharepoint.com/sites/<site_name>
  • URL cartella: https://<company>.sharepoint.com/sites/<site_name>/Shared%20documents/<folder_name>

Usare l'URL del sito o della cartella in uno di questi formati. Non copiare l'indirizzo completo del browser, che può includere valori di percorso o stringa di query non supportati.

  1. Salvare la connessione e quindi copiarne l'ID.
  2. Impostare l'ID connessione su SHAREPOINT_PROJECT_CONNECTION_ID.
  3. Accedi come un utente che disponga almeno di READ di accesso all'ambito SharePoint configurato ed esegui l'agente con l'identità delegata dell'utente.

Verificare il recupero filtrato in base alle autorizzazioni

Verificare sia il recupero riuscito che il recupero negato prima di rendere disponibile l'agente agli utenti:

  1. Scegliere un documento nell'ambito configurato che un utente di test può leggere e un secondo utente di test non può leggere.
  2. Accedere come utente con accesso, porre una domanda la cui risposta si trova in tale documento e verificare che la risposta includa le informazioni previste e una citazione al documento.
  3. Accedere come utente senza accesso e porre la stessa domanda. Verificare che la risposta non includa informazioni o citazioni dal documento con restrizioni.

Eseguire entrambi i controlli con l'autenticazione utente delegata. La risposta del primo utente conferma l’avvenuto recupero; il risultato diverso per il secondo utente conferma che è applicato il filtro delle autorizzazioni di SharePoint.

Supporto per l'utilizzo

La tabella seguente illustra il supporto dell'SDK e della configurazione.

Supporto Foundry di Microsoft PYTHON SDK SDK di C# JavaScript SDK JAVA SDK REST API Configurazione dell'agente di base Configurazione dell'agente standard
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Parametri

Lo strumento SharePoint usa la connessione al progetto per determinare da quale sito o cartella di SharePoint può recuperare informazioni.

Parametro Obbligatorio Note
type Usare sharepoint_grounding_preview.
sharepoint_grounding_preview.project_connections[].project_connection_id Usare il valore di SHAREPOINT_PROJECT_CONNECTION_ID.

Se è necessario creare una connessione SharePoint per il progetto, vedere Aggiungere una nuova connessione al progetto.

Creare un agente con lo strumento SharePoint

Gli esempi dell'SDK usano DefaultAzureCredential. Quando le esegui in locale, questa credenziale deve corrispondere all'identità dell'utente che ha eseguito l'accesso, ad esempio l'identità stabilita da az login. Escludere le credenziali dell'identità gestita e dell'entità servizio dalla catena di credenziali locale. In un'applicazione di produzione, autenticare ogni richiesta con l'identità delegata dell'utente corrente e usare un flusso On-Behalf-Of. Non eseguire le chiamate agli strumenti di SharePoint con l'identità gestita o l'entità di servizio dell'applicazione.

L'esempio seguente illustra come creare un agente che utilizza lo strumento SharePoint per basare le risposte su contenuti da un sito di SharePoint. Selezionare Prompt Agents per usare Azure AI Projects SDK per creare un agente prompt sul lato server o Hosted Agents per usare Agent Framework FoundryChatClient per creare un agente temporaneo in-process.

Agenti rapidi

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
    PromptAgentDefinition,
    SharepointPreviewTool,
    SharepointGroundingToolParameters,
    ToolProjectConnection,
)

# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
SHAREPOINT_CONNECTION_NAME = "my-sharepoint-connection"

# Create clients to call Foundry API
project = AIProjectClient(
    endpoint=PROJECT_ENDPOINT,
    credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()

# Get connection ID from connection name
sharepoint_connection = project.connections.get(
    SHAREPOINT_CONNECTION_NAME,
)

# Configure SharePoint tool with the project connection
sharepoint_tool= SharepointPreviewTool(
    sharepoint_grounding_preview=SharepointGroundingToolParameters(
        project_connections=[
            ToolProjectConnection(project_connection_id=sharepoint_connection.id)
        ]
    )
)

agent = project.agents.create_version(
    agent_name="MyAgent",
    definition=PromptAgentDefinition(
        model="gpt-4.1-mini",
        instructions="""You are a helpful agent that can use SharePoint tools to assist users. 
        Use the available SharePoint tools to answer questions and perform tasks.""",
        tools=[sharepoint_tool],
    ),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")

# Send initial request that will trigger the SharePoint tool
stream_response = openai.responses.create(
    stream=True,
    tool_choice="required",
    input="Please summarize the last meeting notes stored in SharePoint.",
    extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)

for event in stream_response:
    if event.type == "response.created":
        print(f"Follow-up response created with ID: {event.response.id}")
    elif event.type == "response.output_text.delta":
        print(f"Delta: {event.delta}")
    elif event.type == "response.output_text.done":
        print(f"\nFollow-up response done!")
    elif event.type == "response.output_item.done":
        if event.item.type == "message":
            item = event.item
            if item.content[-1].type == "output_text":
                text_content = item.content[-1]
                for annotation in text_content.annotations:
                    if annotation.type == "url_citation":
                        print(
                            f"URL Citation: {annotation.url}, "
                            f"Start index: {annotation.start_index}, "
                            f"End index: {annotation.end_index}"
                        )
    elif event.type == "response.completed":
        print(f"\nFollow-up completed!")
        print(f"Full response: {event.response.output_text}")

Output previsto

Quando si esegue questo codice, viene visualizzato un output simile al seguente:

Agent created (id: asst_abc123, name: MyAgent, version: 1)

Sending request to SharePoint agent with streaming...
Follow-up response created with ID: resp_xyz789
Delta: Based
Delta:  on
Delta:  the
Delta:  meeting
Delta:  notes
...
URL Citation: https://contoso.sharepoint.com/sites/policies/Documents/meeting-notes.docx, Start index: 0, End index: 245

Follow-up response done!

Follow-up completed!
Full response: Based on the meeting notes from your SharePoint site, the last meeting covered the following topics: project timeline updates, budget review, and next quarter planning.

Agenti ospitati

Questo esempio usa FoundryChatClient da Microsoft Agent Framework e chiama get_sharepoint_tool() per collegare una connessione a terra SharePoint. Utilizza AIProjectClient per mappare il nome della connessione a un ID di connessione, quindi esegue un'iterazione sulle annotazioni dei messaggi per visualizzare i riferimenti agli URL. Installare il pacchetto con pip install agent-framework-foundry aiohttp, impostare le FOUNDRY_PROJECT_ENDPOINT variabili di ambiente e FOUNDRY_MODEL e accedere con az login.

import asyncio
import os

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.ai.projects import AIProjectClient
from azure.identity import AzureCliCredential

SHAREPOINT_CONNECTION_NAME = "my-sharepoint-connection"


async def main() -> None:
    credential = AzureCliCredential()
    project = AIProjectClient(
        endpoint=os.environ["FOUNDRY_PROJECT_ENDPOINT"],
        credential=credential,
    )
    sharepoint_connection_id = project.connections.get(SHAREPOINT_CONNECTION_NAME).id

    agent = Agent(
        client=FoundryChatClient(credential=credential),
        instructions="You are a helpful agent. Use the SharePoint tool to answer questions.",
        tools=[FoundryChatClient.get_sharepoint_tool(connection_id=sharepoint_connection_id)],
    )

    result = await agent.run("Please summarize the last meeting notes stored in SharePoint.")
    print(f"Agent: {result.text}")

    for message in result.messages:
        for content in message.contents:
            for annotation in getattr(content, "annotations", None) or []:
                url = getattr(annotation, "url", None)
                if url:
                    title = getattr(annotation, "title", None) or ""
                    print(f"URL Citation: [{title}]({url})")


if __name__ == "__main__":
    asyncio.run(main())

Output previsto

Il testo della risposta viene stampato insieme a tutte le citazioni URL restituite dallo strumento di base SharePoint:

Agent: Based on the meeting notes from your SharePoint site ...
URL Citation: [Meeting notes](https://contoso.sharepoint.com/sites/policies/Documents/meeting-notes.docx)

Per ulteriori informazioni sulle "tool factories" di Agent Framework Foundry, consultare gli esempi del provider Foundry.


L'esempio seguente illustra come creare un agente che utilizza lo strumento SharePoint per basare le risposte su contenuti da un sito di SharePoint. In questo esempio vengono usati metodi sincroni per semplicità. Per una versione asincrona, vedere la documentazione di esempio dell'agente SharePoint nel repository di GitHub dell'Azure SDK per .NET.

Per consentire all'agente di accedere alle SharePoint, usare SharepointPreviewTool. Selezionare Prompt Agents per usare Azure AI Projects SDK per creare un agente prompt sul lato server o Hosted Agents per usare Microsoft Agent Framework per creare un agente temporaneo e in-process.

Agenti rapidi

using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var sharepointConnectionName = "my-sharepoint-connection";

// Create project client to call Foundry API
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: new DefaultAzureCredential());

// Get connection ID from connection name
AIProjectConnection sharepointConnection = projectClient.Connections.GetConnection(connectionName: sharepointConnectionName);

// Use the SharePoint connection ID to initialize the SharePointGroundingToolOptions,
// which will be used to create SharepointPreviewTool. Use this tool to create an Agent.
SharePointGroundingToolOptions sharepointToolOption = new()
{
    ProjectConnections = { new ToolProjectConnection(projectConnectionId: sharepointConnection.Id) }
};
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-4.1-mini")
{
    Instructions = "You are a helpful assistant.",
    Tools = { new SharepointPreviewTool(sharepointToolOption), }
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
    agentName: "myAgent",
    options: new(agentDefinition));

// Create the response and make sure we are always using tool.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
CreateResponseOptions responseOptions = new()
{
    ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
    InputItems = { ResponseItem.CreateUserMessageItem("What is Contoso whistleblower policy") }
};
ResponseResult response = responseClient.CreateResponse(options: responseOptions);

// SharePoint tool can create the reference to the page, grounding the data.
// Create the GetFormattedAnnotation method to get the URI annotation.
string annotation = "";
foreach (ResponseItem item in response.OutputItems)
{
    if (item is MessageResponseItem messageItem)
    {
        foreach (ResponseContentPart content in messageItem.Content)
        {
            foreach (ResponseMessageAnnotation messageAnnotation in content.OutputTextAnnotations)
            {
                if (messageAnnotation is UriCitationMessageAnnotation uriAnnotation)
                {
                    annotation = $" [{uriAnnotation.Title}]({uriAnnotation.Uri})";
                }
            }
        }
    }
}

// Print the Agent output and add the annotation at the end.
Console.WriteLine($"Response status: {response.Status}");
Console.WriteLine($"{response.GetOutputText()}{annotation}");

// After the sample is completed, delete the Agent we have created.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

Output previsto

Quando si esegue questo codice, viene visualizzato un output simile al seguente:

The Contoso whistleblower policy outlines procedures for reporting unethical behavior confidentially. Employees can submit concerns through the ethics hotline or online portal. [Whistleblower Policy](https://contoso.sharepoint.com/sites/policies/Documents/whistleblower-policy.pdf)

L'output include la risposta dell'agente in base al contenuto SharePoint, con un collegamento di citazione al documento di origine.

Agenti ospitati

Questo esempio usa Microsoft Agent Framework e chiama AsAIAgent(...) in AIProjectClient insieme a FoundryAITool.CreateSharepointTool(...) da Microsoft.Agents.AI.Foundry. Installare i pacchetti Microsoft.Agents.AI.Foundry e Azure.AI.Projects, impostare le variabili di ambiente AZURE_AI_PROJECT_ENDPOINT, AZURE_AI_MODEL_DEPLOYMENT_NAME e SHAREPOINT_PROJECT_CONNECTION_ID e accedere con az login.

using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry;

string sharepointConnectionId = Environment.GetEnvironmentVariable("SHAREPOINT_PROJECT_CONNECTION_ID")
    ?? throw new InvalidOperationException("SHAREPOINT_PROJECT_CONNECTION_ID is not set.");
string endpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_AI_PROJECT_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";

const string AgentInstructions = """
    You are a helpful agent that can use SharePoint tools to assist users.
    Use the available SharePoint tools to answer questions and perform tasks.
    """;

var sharepointOptions = new SharePointGroundingToolOptions();
sharepointOptions.ProjectConnections.Add(new ToolProjectConnection(sharepointConnectionId));

AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential());

AIAgent agent = aiProjectClient.AsAIAgent(deploymentName,
    instructions: AgentInstructions,
    name: "SharePointAgent",
    tools: [FoundryAITool.CreateSharepointTool(sharepointOptions)]);

AgentResponse response = await agent.RunAsync("List the documents available in SharePoint");
Console.WriteLine($"Response: {response.Text}");

// Print any URL citations returned by the SharePoint grounding tool.
foreach (AIAnnotation annotation in response.Messages
    .SelectMany(m => m.Contents)
    .SelectMany(c => c.Annotations ?? []))
{
    if (annotation.RawRepresentation is UriCitationMessageAnnotation urlCitation)
    {
        Console.WriteLine($"URL Citation: [{urlCitation.Title}]({urlCitation.Uri})");
    }
}

Output previsto

Il testo della risposta viene stampato insieme a tutte le citazioni URL restituite dallo strumento di SharePoint:

Response: Based on the documents in SharePoint ...
URL Citation: [Whistleblower Policy](https://contoso.sharepoint.com/sites/policies/Documents/whistleblower-policy.pdf)

Per l'esempio completo, vedere Agent_Step19_SharePoint.


Esempio per l'uso di un agente con SharePoint

Ottenere un token di accesso:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

Il campione seguente illustra come creare un agente che utilizza la funzionalità di SharePoint per fondare le risposte su contenuti provenienti da un sito di SharePoint.

curl --request POST \
  --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'",
  "input": "Please summarize the last meeting notes stored in SharePoint.",
  "tool_choice": "required",
  "tools": [
    {
      "type": "sharepoint_grounding_preview",
      "sharepoint_grounding_preview": {
        "project_connections": [
          {
            "project_connection_id": "'$SHAREPOINT_PROJECT_CONNECTION_ID'"
          }
        ]
      }
    }
  ]
}'

Output previsto

L'API restituisce una risposta JSON con le informazioni di risposta e citazione dell'agente:

{
  "id": "resp_abc123xyz",
  "object": "response",
  "created_at": 1702345678,
  "status": "completed",
  "output": [
    {
      "id": "msg_abc123xyz",
      "type": "message",
      "role": "assistant",
      "status": "completed",
      "content": [
        {
          "type": "output_text",
          "text": "Based on the meeting notes...",
          "annotations": [
            {
              "type": "url_citation",
              "url": "https://contoso.sharepoint.com/sites/policies/Documents/meeting-notes.docx",
              "start_index": 0,
              "end_index": 245
            }
          ]
        }
      ]
    }
  ]
}

Questo esempio illustra come creare un agente di intelligenza artificiale con funzionalità di SharePoint. L'agente può cercare il contenuto di SharePoint e fornire risposte con informazioni pertinenti provenienti dai siti di SharePoint. Per una versione JavaScript, vedere la documentazione di esempio dell'agente SharePoint nel repository Azure SDK per JavaScript GitHub.

import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";

// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const SHAREPOINT_CONNECTION_NAME = "my-sharepoint-connection";

export async function main(): Promise<void> {
  // Create clients to call Foundry API
  const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
  const openai = project.getOpenAIClient();

  // Get connection ID from connection name
  const sharepointConnection = await project.connections.get(SHAREPOINT_CONNECTION_NAME);

  // Create agent with SharePoint tool
  const agent = await project.agents.createVersion("MyAgent", {
    kind: "prompt",
    model: "gpt-4.1-mini",
    instructions:
      "You are a helpful agent that can use SharePoint tools to assist users. Use the available SharePoint tools to answer questions and perform tasks.",
    // Define SharePoint tool that searches SharePoint content
    tools: [
      {
        type: "sharepoint_grounding_preview",
        sharepoint_grounding_preview: {
          project_connections: [
            {
              project_connection_id: sharepointConnection.id,
            },
          ],
        },
      },
    ],
  });
  console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);

  // Send initial request that will trigger the SharePoint tool
  const streamResponse = await openai.responses.create(
    {
      input: "Please summarize the last meeting notes stored in SharePoint.",
      stream: true,
    },
    {
      body: {
        agent_reference: { name: agent.name, type: "agent_reference" },
        tool_choice: "required",
      },
    },
  );

  // Process the streaming response
  for await (const event of streamResponse) {
    if (event.type === "response.created") {
      console.log(`Follow-up response created with ID: ${event.response.id}`);
    } else if (event.type === "response.output_text.delta") {
      process.stdout.write(event.delta);
    } else if (event.type === "response.output_text.done") {
      console.log("\n\nFollow-up response done!");
    } else if (event.type === "response.output_item.done") {
      if (event.item.type === "message") {
        const item = event.item;
        if (item.content && item.content.length > 0) {
          const lastContent = item.content[item.content.length - 1];
          if (lastContent.type === "output_text" && lastContent.annotations) {
            for (const annotation of lastContent.annotations) {
              if (annotation.type === "url_citation") {
                console.log(
                  `URL Citation: ${annotation.url}, Start index: ${annotation.start_index}, End index: ${annotation.end_index}`,
                );
              }
            }
          }
        }
      }
    } else if (event.type === "response.completed") {
      console.log("\nFollow-up completed!");
    }
  }

  // Clean up resources
  await project.agents.deleteVersion(agent.name, agent.version);
}

main().catch((err) => {
  console.error("The sample encountered an error:", err);
});

Output previsto

Quando si esegue questo codice, viene visualizzato un output simile al seguente:

Creating agent with SharePoint tool...
Agent created (id: asst_abc123, name: MyAgent, version: 1)

Sending request to SharePoint agent with streaming...
Follow-up response created with ID: resp_xyz789
Based on the meeting notes from your SharePoint site, the last meeting covered the following topics: project timeline updates, budget review, and next quarter planning.

Follow-up response done!
URL Citation: https://contoso.sharepoint.com/sites/policies/Documents/meeting-notes.docx, Start index: 0, End index: 245

Follow-up completed!

Cleaning up resources...
Agent deleted

SharePoint agent sample completed!

Utilizzare l'integrazione di SharePoint in un agente Java

Aggiungi la dipendenza a pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.4.0</version>
</dependency>

Creare un agente basato su SharePoint

import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.*;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;

import java.util.Arrays;
import java.util.Collections;

public class SharePointGroundingExample {
    public static void main(String[] args) {
        // Format: "https://resource_name.ai.azure.com/api/projects/project_name"
        String projectEndpoint = "your_project_endpoint";
        String sharepointConnectionId = "your_sharepoint_connection_id";

        AgentsClientBuilder builder = new AgentsClientBuilder()
            .credential(new DefaultAzureCredentialBuilder().build())
            .endpoint(projectEndpoint);

        AgentsClient agentsClient = builder.buildAgentsClient();
        ResponsesClient responsesClient = builder.buildResponsesClient();

        // Create SharePoint grounding tool with connection configuration
        SharepointPreviewTool sharepointTool = new SharepointPreviewTool(
            new SharepointGroundingToolParameters()
                .setProjectConnections(Arrays.asList(
                    new ToolProjectConnection(sharepointConnectionId)
                ))
        );

        // Create agent with SharePoint tool
        PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-4.1-mini")
            .setInstructions("You are a helpful assistant that can search through SharePoint documents.")
            .setTools(Collections.singletonList(sharepointTool));

        AgentVersionDetails agent = agentsClient.createAgentVersion("sharepoint-agent", agentDefinition);
        System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());

        // Create a response
        AgentReference agentReference = new AgentReference(agent.getName())
            .setVersion(agent.getVersion());

        Response response = responsesClient.createAzureResponse(
            new AzureCreateResponseOptions().setAgentReference(agentReference),
            ResponseCreateParams.builder()
                .input("Find the latest project documentation in SharePoint"));

        System.out.println("Response: " + response.output());

        // Clean up
        agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
    }
}

Limitazioni

  • Lo strumento SharePoint supporta solo l'autenticazione dell'identità utente. L'autenticazione tramite applicazione (entità servizio) non è supportata.
  • Il sito SharePoint e l'agente foundry Microsoft devono trovarsi nello stesso tenant.
  • È possibile aggiungere un solo strumento SharePoint per agente.
  • L'API di recupero Microsoft 365 Copilot sottostante restituisce estratti di testo. Il recupero da contenuto non testuale, incluse immagini e grafici, non è supportato.
  • Per il recupero semantico e ibrido, l'API di recupero Microsoft 365 Copilot supporta .doc, .docx, .pptx, .pdf, .aspx e .one tipi di file. Per informazioni dettagliate, vedere l'API Microsoft 365 Copilot.
  • L'API di recupero sottostante restituisce al massimo 25 risultati e consente 200 richieste per utente all'ora. La stringa di query può contenere al massimo 1.500 caratteri.

Come funziona

Lo strumento SharePoint consente di abilitare integrazioni semplici tra agenti di intelligenza artificiale e documenti aziendali archiviati in SharePoint. Questa funzionalità è abilitata dall'API Microsoft 365 Copilot. Per mettere a terra i documenti SharePoint, immettere i siti o le cartelle con cui connettersi. Lo strumento SharePoint sfrutta funzionalità di indicizzazione predefinite per migliorare l'esperienza di ricerca e recupero, tra cui indicizzazione intelligente, elaborazione di query e suddivisione in blocchi del contenuto.

Per ulteriori informazioni sull'accesso delegato e sul pass-through delle identità in Foundry, consultare Concetti di identità dell'agente in Microsoft Foundry.

Anziché richiedere agli sviluppatori di esportare SharePoint contenuto, creare un indice semantico personalizzato, gestire i controlli di governance e configurare la logica di aggiornamento, questa funzionalità automatizza l'intera pipeline di recupero. Indicizza in modo dinamico i documenti, suddivide il contenuto in blocchi significativi e applica l'elaborazione avanzata delle query per visualizzare le informazioni più rilevanti. Usando lo stesso stack di recupero di livello aziendale che supporta Microsoft 365 Copilot, questa funzionalità garantisce che le risposte dell'agente di intelligenza artificiale siano basate sul contenuto più up-to-date e contestualmente pertinente.

I clienti si basano sulla sicurezza dei dati in SharePoint per accedere, creare e condividere documenti con un controllo di accesso flessibile a livello di documento. Le funzionalità aziendali, ad esempio il pass-through dell'identità (On-Behalf-Of), consentono di garantire un controllo di accesso appropriato. Gli utenti finali ricevono risposte generate da SharePoint documenti a cui hanno l'autorizzazione per accedere. Usando l'autenticazione OBO, foundry Agent Service usa l'identità dell'utente finale per autorizzare e recuperare i documenti di SharePoint pertinenti, generando risposte personalizzate per utenti finali specifici.

Risoluzione dei problemi

Problema Causa Risoluzione
AuthenticationError: AppOnly OBO tokens not supported by target service Uso dell'identità dell'applicazione anziché dell'identità utente Lo strumento SharePoint richiede l'identità utente (passaggio dell'identità). Non utilizzare l'autenticazione basata solo sull'applicazione.
Forbidden: Authorization Failed - User does not have valid license Licenza Microsoft 365 Copilot mancante o modello con pagamento in base al consumo Assegnare una licenza Microsoft 365 Copilot all'utente o abilitare il pagamento in base al consumo. Vedere Prerequisiti.
Errori di autenticazione o 401 Tentativo di accesso tra diversi tenant Verificare che l'utente in Foundry e Microsoft 365 si trovi nello stesso tenant.
Lo strumento non restituisce risultati L'utente non ha accesso al contenuto SharePoint Verificare che l'utente disponga dell'accesso in lettura ai siti e ai documenti di SharePoint sottoposti a query.
Tempi di risposta lenti Ambito di ricerca di documenti di grandi dimensioni Restringere l'ambito di ricerca specificando siti o librerie specifici. Prendere in considerazione l'uso di query di ricerca più specifiche.
Recupero di documenti incompleti Contenuto non indicizzato Verificare che il contenuto SharePoint sia indicizzato da Microsoft Search. Il contenuto aggiunto di recente potrebbe richiedere tempo per l'indicizzazione.
Resource not found Errori Percorso del sito o della libreria non valido Verificare che l'URL del sito SharePoint e i percorsi di libreria siano corretti e accessibili all'utente.
Risultati della ricerca incoerenti Ritardo di sincronizzazione dell'indice semantico Attendere la sincronizzazione dell'indice semantico. La propagazione di modifiche di contenuto di grandi dimensioni potrebbe richiedere tempo. Consulta l'indicizzazione semantica per Microsoft 365 Copilot.