Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Interact with the Grok API, by xAI, using an SDK written for use in Swift.

License

NotificationsYou must be signed in to change notification settings

Visual-Studio-Coder/Grok-API-SDK

Repository files navigation

SwiftPlatformLicense

Using this SDK, you can interact with Elon Musk's new AI! This SDK provides methods to interact with various endpoints of the Grok API, including fetching API key information, listing models, and creating chat completions.

Installation

To install the Grok API Swift SDK, add the following dependency to yourPackage.swift file:

// swift-tools-version: 6.0import PackageDescriptionletpackage=Package(    name:"Grok-API-SDK",    platforms:[.iOS(.v12),.macOS(.v12)],    products:[.library(            name:"Grok-API-SDK",            targets:["Grok-API-SDK"]),],    targets:[.target(            name:"Grok-API-SDK"),.testTarget(            name:"Grok-API-SDKTests",            dependencies:["Grok-API-SDK"]),])

Usage

Initialization

First, initialize theGrokAPI class with your API key. It is recommended to use environment variables to manage your API keys securely:

import Grok_API_SDKletapiKey=ProcessInfo.processInfo.environment["GROK_API_KEY"]??"your_api_key_here"letapi=GrokAPI(apiKey: apiKey)

Fetch API Key Information

You can fetch information about your API key using thegetAPIKeyInfo method:

api.getAPIKeyInfo{ resultinswitch result{case.success(let apiKeyInfo):print("API Key Info:\(apiKeyInfo)")case.failure(let error):print("Error:\(error.localizedDescription)")}}

List Models

You can list available models using thelistModels method:

api.listModels{ resultinswitch result{case.success(let modelList):print("Models:\(modelList)")case.failure(let error):print("Error:\(error.localizedDescription)")}}

Create Chat Completion

You can create a chat completion using thecreateChatCompletion method. This method requires aChatCompletionRequest object, which includes the model name and a list of messages:

letmessages=[ChatMessage(role:"user", content:"Hello, how are you?")]letrequest=ChatCompletionRequest(    model:"grok-beta",    messages: messages,    maxTokens:150,    temperature:0.7)api.createChatCompletion(request: request){ resultinswitch result{case.success(let response):print("Chat Completion Response:\(response)")case.failure(let error):print("Error:\(error.localizedDescription)")}}

Create Chat Completion with Function Calling

You can create a chat completion with function calling using thecreateChatCompletionWithFunctionCallAsync method. This method allows the assistant to call predefined functions to perform specific tasks:

letmessages=[ChatMessage(role:"system", content:"You are a helpful assistant that can perform calculations."),ChatMessage(role:"user", content:"What is 5027 * 3032? Use the calculator tool.")]letcalculatorFunction=Function(    type:"function",    name:"calculator",    parameters:FunctionParameters(        type:"object",        properties:["a":FunctionParameter(type:"number", description:"The first operand", exampleValue:"5027"),"b":FunctionParameter(type:"number", description:"The second operand", exampleValue:"3032")],        required:["a","b"]))letrequest=ChatCompletionRequest(    model:"grok-beta",    messages: messages,    maxTokens:150,    temperature:0.7,    toolChoice:"auto",    tools:[calculatorFunction.name])Task{do{letresponse=tryawait api.createChatCompletionWithFunctionCallAsync(request: request, tools:[calculatorFunction])print("Chat Completion Response:\(response)")}catch{print("Error:\(error.localizedDescription)")}}

Streaming Chat Completions

To provide a seamless and interactive user experience, the Grok API Swift SDK supports streaming responses. This allows you to receive partial results in real-time as the model generates content.

letrequest=ChatCompletionRequest(    model:"grok-beta",    messages: messages,    maxTokens:150,    temperature:0.7,    stream:true,    toolChoice:"auto",    tools:[calculatorFunction.name])Task{do{varfinalResponseContent:String=""fortryawaitchunkin api.createChatCompletionStream(request: request){print(chunk, terminator:"") // Print partial content            finalResponseContent+= chunk}print("\nFinal response content:\(finalResponseContent)")}catch{print("Error:\(error.localizedDescription)")}}

Structured Output

The Grok API Swift SDK supports structured outputs, allowing you to define the expected format of the response using JSON Schema. This ensures that the response adheres to a specific structure, making it easier to parse and use in your application.

letmessages=[ChatMessage(role:"system", content:"You are an assistant helping the user rate movies."),ChatMessage(role:"user", content:"What is the rating of Star Wars?")]letschemaProperties:[String:SchemaProperty]=["title":SchemaProperty(type:"string", description:nil),"rating":SchemaProperty(type:"number", description:"The rating of the movie, typically out of 10"),"summary":SchemaProperty(type:"string", description:nil)]letrequest=ChatCompletionRequest(    model:"grok-2-1212",    messages: messages,    maxTokens:150,    temperature:0.7,    responseFormat:ResponseFormat(        type:"json_schema",        jsonSchema:JSONSchema(            name:"movie_response",            schema:SchemaDetails(                type:"object",                properties: schemaProperties,                required:["title","rating","summary"],                additionalProperties:false),            strict:true)))api.createChatCompletion(request: request){ resultinswitch result{case.success(let response):print("Structured Output Response:\(response)")case.failure(let error):print("Error:\(error.localizedDescription)")}}

Error Handling

The SDK provides detailed error messages to help you understand any issues that arise. Errors are returned as instances of theGrokAPIError enum, which conforms to theLocalizedError protocol:

publicenumGrokAPIError:Error,LocalizedError{case invalidResponsecase httpError(Int,Data?)case noDatacase decodingError(Error)case custom(String)publicvarerrorDescription:String?{switchself{case.invalidResponse:return"Invalid response from the server."case.httpError(let statusCode,let data):iflet data= data,let responseString=String(data: data, encoding:.utf8){return"HTTP Error:\(statusCode). Response:\(responseString)"}else{return"HTTP Error:\(statusCode). Please check your API key and endpoint."}case.noData:return"No data received from the server."case.decodingError(let error):return"Decoding error:\(error.localizedDescription). Please check the response format."case.custom(let message):return message}}}

Troubleshooting

Common Issues

Invalid API Key

Symptoms: ReceivingHTTP Error: 401 or similar authentication errors.
Solution: Ensure that your API key is correct and has the necessary permissions. You can verify your API key using thegetAPIKeyInfo method.

Decoding Errors

Symptoms: Errors related to JSON decoding, such as missing keys or type mismatches.
Solution:

  • Verify that the API response structure matches the models defined in the SDK.
  • Ensure that all required parameters are provided in function calls.
  • Check for updates in the API that might introduce new fields or change existing ones.
Network Connectivity Issues

Symptoms: Timeouts or inability to reach the API server.
Solution:

  • Check your internet connection.
  • Ensure that there are no firewalls or proxies blocking the requests.
  • Retry the request after some time in case of temporary server issues.
Missing Function Definitions

Symptoms: The assistant attempts to call a function that is not defined or provided in thetools list.
Solution:

  • Ensure that all required functions are defined and included in thetools array when making theChatCompletionRequest.
  • Verify the function parameters and their types are correctly specified.

Getting Help

If you encounter issues not covered in this section, please open an issue on theGitHub repository or contact the maintainer directly.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License.


Copyright © 2024-2025 Vaibhav Satishkumar. All rights reserved.

About

Interact with the Grok API, by xAI, using an SDK written for use in Swift.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp